refactor(backend): standardize errors and simplify configuration and test setup

This commit is contained in:
TakuyaYagam1 committed 2026-10-05 16:15:30 +03:00
1 parent 1535c19b8c
commit 138666a7bb
92 files changed
+3994 -210

No files matched your search

+17 -11
View File
@@ -1,10 +1,10 @@
# Lincodex architecture
This document separates the target product architecture from the technical scaffold in the repository. The requirements source is ФСП спец. трек ТЗ.pdf at the repository root. Page references in the coverage table use the printed pagination without the cover page. The team supplied October 11 and October 30, 2026, as project milestones.
This document separates the target product architecture from the technical scaffold in the repository. The requirements source is the [specification](../../requirements/specification.pdf). Page references in the coverage table use the printed pagination without the cover page. The [brandbook](../../requirements/brandbook/) is stored alongside the specification. The team supplied October 11 and October 30, 2026, as project milestones.
## Current scaffold
The repository contains a Go HTTP service with a PostgreSQL check, a minimal React status page, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a minimal React status page, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
This is an operational scaffold. It has no registration, roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, or FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
@@ -12,7 +12,7 @@ See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTIN
## Target system
The target is a modular Go backend with Clean Architecture, a React SPA using Vite and FSD, and a separate ML HTTP service in one repository. The planned Go process runs the HTTP API and background worker together. PostgreSQL stores product records and jobs. Private file storage holds resumes and generated PDFs. The initial target uses Docker Compose on one application host, with ML in a separate environment.
The target is a modular Go backend with Clean Architecture, a React SPA using Vite and FSD, and a separate ML HTTP service in one repository. The planned Go process runs the HTTP API and background worker together. PostgreSQL stores product records and jobs; Redis provides the cache. Private S3-compatible SeaweedFS storage is selected for resumes and generated PDFs; the file workflows are not implemented yet. The initial target uses Docker Compose on one application host, with ML in a separate environment.
Go owns authorization, verified categories, invitations, contact grants, and final search results. ML proposes resume fields, helps interpret employer needs, and can take part in semantic search experiments. Model outages must leave manual profiles, assessments, filter-based search, and invitations available.
@@ -42,11 +42,15 @@ The planned backend boundaries are:
- Bootstrap wires implementations and controls process startup and shutdown.
- Product rules stay in domain and usecase code, away from chi handlers, workers, SQL, and ML.
Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0 and httpkit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT, cache, or WebSocket dependencies for hypothetical features.
Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0, httpkit 0.7.0, and cachekit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT or WebSocket dependencies for hypothetical features.
PostgreSQL with pgx, sqlc, and goose remains the planned database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment.
The MVP does not add Redis, a separate vector database, a broker, Kubernetes, or a search microservice. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
Redis is part of the core Compose project and connects through `backend/internal/adapter/secondary/redis/` to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet.
SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. Resume uploads, authorization, content limits, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup.
The MVP does not add a separate vector database, a broker, Kubernetes, or a search microservice. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
## Repository map and package purpose
@@ -80,7 +84,7 @@ backend/
domain/ flat package; currently only .gitkeep
usecase/health/ operational readiness usecase
port/inbound/ readiness input boundary
port/outbound/ database readiness boundary
port/outbound/ readiness, cache, and object storage boundaries
adapter/primary/http/
api/ generated ogen handler
middleware/ request metrics
@@ -89,6 +93,8 @@ backend/
adapter/secondary/
ml/api/ generated client from backend/codegen/ogen-ml.yml
postgres/sqlc/ generated SQL adapter
redis/ cache adapter and Redis check
seaweedfs/ S3 adapter and bucket check
prometheus/ bounded Go/process and request metrics
bootstrap/ configuration, wiring, lifecycle, shutdown
db/ migrations and SQL queries; no product schema yet
@@ -98,11 +104,11 @@ backend/
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. Until the types are defined, the directory contains only `.gitkeep`.
Product domain types and usecase modules, file/mail/FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
Product domain types and usecase modules, mail/FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap, and a PostgreSQL health query. Accounts, resumes, assessments, invitations, worker jobs, storage, mail, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap, a PostgreSQL health query, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers; a `storagepath` helper is optional if local file storage is selected. Keep service-specific behavior private under `internal/`.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
@@ -228,9 +234,9 @@ Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amo
## Metrics, telemetry, and alerts
The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. Queue, inference, and product-event metrics are not implemented in the current scaffold.
The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. Queue, inference, and product-event metrics are not implemented in the current scaffold.
Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx `stub_status` does not provide latency by HTTP status; access logs can provide `request_time` and `upstream_response_time`. cAdvisor is optional if the selected runtime supports it. Redis and DCGM exporters belong only with actual Redis or a local NVIDIA model.
Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx `stub_status` does not provide latency by HTTP status; access logs can provide `request_time` and `upstream_response_time`. cAdvisor is optional if the selected runtime supports it. Redis exporter is included in the separate monitoring Compose project; Prometheus scrapes its internal port 9121. SeaweedFS metrics are scraped directly on internal port 9327, retaining only selected aggregate series without object paths. DCGM exporter is only needed with a local NVIDIA model.
The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported.
+19 -6
View File
@@ -9,13 +9,13 @@ Install Docker Engine and the Docker Compose plugin. At the repository root, cop
make -C deploy config
make -C deploy up
deploy/docker/docker-compose.yml starts PostgreSQL, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Go, and Nginx communicate on the Compose network.
deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Redis, SeaweedFS, Go, and Nginx communicate on the Compose network.
The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context.
The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data.
Open http://127.0.0.1:8080. The host port binds to loopback. Nginx handles /healthz, proxies /api/ to Go, and uses the SPA fallback for other paths. The Go health endpoint is /api/v1/healthz; Go readiness checks PostgreSQL with SELECT 1. The internal backend port 9090 serves /metrics.
Open http://127.0.0.1:8080. The host port binds to loopback. Nginx handles /healthz, proxies /api/ to Go, and uses the SPA fallback for other paths. The Go health endpoint is /api/v1/healthz; the internal Go /readyz checks PostgreSQL with SELECT 1, Redis with PING, and the SeaweedFS bucket with HeadBucket; any dependency being unavailable produces 503. The internal backend port 9090 serves /metrics.
This Nginx configuration has no production TLS. The current bind does not expose the app directly to the public network. Remote access needs a selected TLS reverse proxy, firewall rules, and environment-specific configuration.
@@ -27,11 +27,23 @@ Useful commands:
make -C deploy down
make -C deploy smoke
Redis uses `redis:alpine`, the `REDIS_PASSWORD` value from `.env`, and the internal `redis:6379` address; it publishes no host port. Data is limited to 128 MB with `allkeys-lru` eviction, and the container memory limit is 256 MB. RDB and AOF are disabled with no persistent volume: restarting Redis clears the cache. Do not keep the only copy of a record there. The backend and Redis exporter both require its password.
Backend settings are `REDIS_ADDR`, `REDIS_PASSWORD`, `REDIS_DB`, and `REDIS_TIMEOUT`. Compose supplies `redis:6379`; a directly launched Go process defaults to `localhost:6379`, DB 0, and a 1s timeout. Provide a separately reachable Redis address for direct execution because the current Compose does not publish Redis outside its network.
SeaweedFS uses `chrislusf/seaweedfs:latest` with `weed mini`: master, volume, filer, and S3 API share one container. The named `seaweedfs_data` volume mounts at `/data` and preserves object content and metadata. S3 is reachable only inside the network at `http://seaweedfs:8333`, with no published host port. WebDAV, Admin UI, IAM API, Iceberg, and Lance are disabled. Nginx continues to serve the frontend and `/api`; there is no direct object route.
Set `SEAWEEDFS_ACCESS_KEY` and `SEAWEEDFS_SECRET_KEY` in `.env`, replacing the example values. Compose passes them to the server as `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, and passes `SEAWEEDFS_BUCKET` as `S3_BUCKET` to initialize the bucket at startup. This is one administrative credential pair for the local stack, not production service-level access separation. Never provide it to browser clients.
Backend settings are `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SECRET_KEY`, `SEAWEEDFS_BUCKET`, `SEAWEEDFS_REGION`, and `SEAWEEDFS_TIMEOUT`. Compose supplies endpoint `http://seaweedfs:8333`; a directly launched Go process defaults to `http://localhost:8333`, bucket `lincodex`, region `us-east-1`, and timeout `10s`. Credentials are required. Direct execution needs a separately reachable private endpoint. Readiness checks the bucket; the backend does not create it.
Ordinary `down` preserves the SeaweedFS volume. Losing the volume loses both objects and metadata; prepare a verified backup before changing the image or deleting the volume. This is one node without HA, cross-node replication, or configured off-host backups.
down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop.
## Separate ML Compose project
ML uses a separate Compose file and project. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
make -C deploy ml-config
make -C deploy ml-up
@@ -51,7 +63,7 @@ Start the core project first. Monitoring joins its Docker network. Monitoring st
Grafana is available at http://127.0.0.1:3000. Credentials come from GRAFANA_ADMIN_USER and GRAFANA_ADMIN_PASSWORD in .env. Prometheus, Loki, exporters, and backend metrics publish no host ports.
Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, and postgres. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs.
Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, postgres, redis, and seaweedfs. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs.
Frontend telemetry is not connected in the React app yet. Nginx and Alloy provide a restricted /telemetry receiver and Faro configuration, but the UI SDK and end-to-end event check are absent.
@@ -68,6 +80,7 @@ Container images use moving `latest` or `alpine` tags where the upstream publish
| Component | Current image source | Principal upstream license |
| --- | --- | --- |
| PostgreSQL | Docker Official Image, docker-library/postgres | PostgreSQL License for the server; packaging repository is MIT |
| SeaweedFS | chrislusf/seaweedfs | [Apache-2.0](https://github.com/seaweedfs/seaweedfs/blob/master/LICENSE) |
| Prometheus | prom/prometheus | Apache-2.0 |
| Loki | grafana/loki | AGPL-3.0-only by default; see LICENSING.md exceptions |
| Grafana Alloy | grafana/alloy | Apache-2.0 by default |
@@ -85,9 +98,9 @@ The backend builds with Go 1.26.8; its runtime image is selected in backend/Dock
## Observability configuration
Prometheus scrapes backend /metrics on port 9090, PostgreSQL exporter, node exporter, itself, and the optional ML target. Loki uses a single-binary filesystem store with 168-hour retention. Grafana provisions Prometheus and Loki datasources from observability/grafana/provisioning/.
Prometheus scrapes backend /metrics on port 9090, PostgreSQL exporter, Redis exporter on port 9121, SeaweedFS on port 9327, node exporter, itself, and the optional ML target. Loki uses a single-binary filesystem store with 168-hour retention. Grafana provisions Prometheus and Loki datasources from observability/grafana/provisioning/.
The three checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, and Linux system. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
The five checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux system. The Redis dashboard covers availability, memory, cache hits/misses, evictions/expired keys, and client connections. The exporter collects aggregate metrics without scanning keys. The SeaweedFS dashboard covers availability, S3 request rate and duration, errors, disk, and memory; Prometheus retains only selected aggregate metrics without object paths. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
The local monitoring stack is a single-node development/demo setup and provides no HA. Compose validation does not establish production retention, off-host backups, public access control, alert delivery, or core application behavior.
+30 -1
View File
@@ -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.
+47
View File
@@ -0,0 +1,47 @@
# Security checks
The repository provides local and CI checks for known dependency vulnerabilities, selected configuration risks, secrets, and selected unsafe source patterns. These checks cover the technical scaffold. They do not establish complete security or verify future authorization and personal-data workflows.
## Commands
Run from the repository root:
```sh
make -C security install
make -C security check
make -C security test
make -C security images
```
Installation requires Python, uv, Go, and network access. The Trivy/Gitleaks binary installer supports Linux amd64 and arm64. Tools stay in `security/.bin/`, `.tools/`, and `.cache/`; installation does not change global tools. The installer selects current stable Trivy and Gitleaks releases and verifies their downloaded archives against upstream SHA256 checksums. govulncheck is installed with `go install ...@latest`. Semgrep uses an isolated uv tool environment with Python 3.13; uv stores its managed Python under `security/.tools/python/`. Tool versions may change on a later installation; inspect installation output when reproducing a finding.
| Target | Scope |
| --- | --- |
| `filesystem` | Trivy scans repository dependencies and configuration with `trivy/filesystem.yml` |
| `secrets` | Gitleaks scans current files and all available Git history with `gitleaks/gitleaks.toml` |
| `go` | govulncheck analyzes the backend's use of known vulnerable Go code |
| `semgrep` | Local rules in `semgrep/frontend.yml` and `semgrep/python.yml` inspect frontend and ML source |
| `rule-test` | Semgrep fixtures check expected matches and non-matches for the local rules |
| `test` | Runs Semgrep rule fixtures and tests for installer integrity, preservation of govulncheck failure status, and removal of stale reports |
| `check` | Runs filesystem, secrets, Go, and Semgrep checks; attempts every check and returns failure if any fails |
| `images` | Builds backend, frontend, and ML images, then scans each exact local image ID with Trivy |
Gitleaks requires a full Git checkout. A missing repository or shallow history fails the check rather than silently omitting history. Reports redact detected secret values. Developer tool caches and build output are excluded where configured; application lockfiles remain scan inputs. Trivy also recognizes `requirements-*.txt`, including `backend/requirements-quality.txt` and `scripts/requirements-codegen.txt`.
Image checks require Docker. The backend build context is `backend/`; frontend and ML use the repository root. Images are tagged `lincodex-security-<service>:local` and resolved to image IDs before scanning. This command does not start containers or publish images. Scanning frontend source dependencies remains necessary because the final Nginx image contains compiled assets rather than the development dependency tree.
## Findings and exceptions
Trivy findings of severity `HIGH` or `CRITICAL` fail the check, including findings without a published fix, unless an active, narrowly scoped exception applies. Gitleaks findings, configured Semgrep findings, govulncheck findings, and scanner errors also fail their targets. The existing Go lint configuration retains gosec; this complements the added checks.
Review the reported package, installed version, affected path, and available remediation before changing dependencies or configuration. Keep reports local: `security/reports/` is ignored. govulncheck uses text output so its native failure status is preserved.
One temporary exception in [security/trivy/ignore.yml](../../security/trivy/ignore.yml) was approved by the project owner on 2026-10-05: `CVE-2026-93687` for `pkg:npm/braces@3.0.3` in `frontend/pnpm-lock.yaml`. At approval, no fixed release was available; the exception unblocks dependency CI until its expiry on 2026-10-19. Project maintainers own the exception and must remove it when a fix becomes available or review it before expiry. Trivy enforces the expiry date. Only filesystem scanning uses this exception file; suppressed findings remain visible in its JSON report. Image scanning is unaffected.
For any further exception, scope it to the specific finding and affected input, record the reason, owner, and expiry, and have the change reviewed. The current integration does not enforce expiry uniformly across every tool, so review expiry explicitly where needed. Do not disable an entire scanner or globally suppress unfixed vulnerabilities to obtain a passing result.
## CI and limits
CI runs `make -C security test check` for source checks and `make -C security images` for images, and includes both jobs in its required aggregate result. Reports are uploaded as artifacts with a 14-day retention period, including when checks fail. Gitleaks redacts secret values, but reports can still reveal repository paths and dependency details; restrict artifact access accordingly.
The local Semgrep rules are a bounded frontend/ML rule set, not a complete application audit. Scanner results depend on the actual checkout, rule versions, vulnerability databases, build inputs, and time of execution. Checked-in workflows do not prove that a GitHub run occurred or that the current tree is free of findings. Record actual results when preparing a release; see [TESTING.md](TESTING.md) for other validation boundaries.
+28 -4
View File
@@ -20,7 +20,7 @@ Useful focused commands:
| make -C api check | Schema merge, bundles, OpenAPI lint, merge-script tests |
| make -C backend test | Go unit suite with race detector |
| make -C backend test-fast | Faster Go tests without race instrumentation |
| make -C backend test-int | Go integration tests with Testcontainers/PostgreSQL |
| make -C backend test-int | Go integration tests with Testcontainers/PostgreSQL/Redis/SeaweedFS |
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries, build |
| make -C ml check | Ruff, mypy, pytest, and wheel build |
| make -C ml check-generated | Pydantic models match the ML bundle without rewriting files |
@@ -32,19 +32,43 @@ make -C deploy test-e2e is reserved and currently exits nonzero with a message t
make -C ml check-generated uses datamodel-code-generator --check: a mismatch fails the check and leaves the models file unchanged. Prepare the bundle with make -C api bundle before checking; use make -C ml generate to update Python models. Generated models do not establish inference functionality or support for every OpenAPI 3.2 feature.
Security checks run separately: `make -C security check` scans source/dependencies/secrets, `make -C security test` validates local Semgrep fixtures, installer integrity, and govulncheck failure handling, and `make -C security images` builds and scans all three service images. Install tools with `make -C security install` first. Scanner failure is a failed check, not a clean result. See [SECURITY.md](SECURITY.md) for Git/Docker requirements, blocking findings, and CI reports.
## Current scaffold coverage
Existing checks cover health/readiness, backend PostgreSQL connectivity, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior.
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior.
API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub.
Deployment smoke checks infrastructure routes and Compose startup. It does not check contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, and rejection of anonymous SeaweedFS bucket access. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It does not check contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
## Integration test bootstrap
The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling `env := bootstrap(t)` starts PostgreSQL, Redis, and SeaweedFS, waits for adapter readiness, and returns an environment with configuration and clients. To test one adapter, use `bootstrap(t, postgresService)`, `bootstrap(t, redisService)`, or `bootstrap(t, seaweedfsService)`. Multiple services can be selected.
Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable.
Bootstrap starts infrastructure and clients. The application HTTP server, business-schema migrations, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness.
## Integration test sharding
`make -C backend test-int` runs the full suite through `backend/scripts/run-integration-suite.py`. The runner discovers every top-level `Test*` in `./integration_test/...`, sorts by package and name, and distributes tests round-robin. Each test belongs to exactly one shard with all its subtests. Changing the test set may change the assignment; duration-based balancing is not implemented.
```sh
make -C backend test-int-list
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
```
Indexes start at 1. Set both variables together; invalid settings, an empty suite, excess shards, and discovery failures fail the command. `test-int-list` compiles test packages and lists selected tests without starting containers. `make -C backend test-scripts` verifies complete, disjoint coverage, parent-test selection, and runner failure propagation. It is included in `make -C backend check`.
CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database. Increase the matrix size together with `TEST_SHARD_TOTAL` when suite duration warrants more runners.
## Future software validation
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
Isolate test data by database/schema or run scenarios with a sequential reset. Do not run parallel cases against shared truncation. Start containers per suite, use dynamic ports, and clean them up. Integration CI must not silently skip tests when its container runtime is unavailable.
Isolate test data by database/schema or run scenarios with a sequential reset. Do not run parallel cases against shared truncation. Reuse the bootstrap environment within a parent test; independent tests create their own environments. Integration CI must not silently skip tests when its container runtime is unavailable.
Validate contract changes with bundle, lint, codegen for every Go, TypeScript, and Python consumer, and generated drift, including new untracked files. Frontend component tests do not replace browser tests of the complete flow. After product implementation, add Playwright for both roles and a synthetic candidate without FSP history.
+17 -11
View File
@@ -1,10 +1,10 @@
# Архитектура Lincodex
Документ описывает целевую платформу и отделяет ее от технического каркаса, который уже есть в репозитории. Основание требований - файл "ФСП спец. трек ТЗ.pdf" в корне; номера страниц в матрице относятся к печатной нумерации без обложки. Сроки 11 и 30 октября 2026 года переданы командой.
Документ описывает целевую платформу и отделяет ее от технического каркаса, который уже есть в репозитории. Основание требований - [ТЗ](../../requirements/specification.pdf); номера страниц в матрице относятся к печатной нумерации без обложки. [Брендбук](../../requirements/brandbook/) хранится рядом с ТЗ. Сроки 11 и 30 октября 2026 года переданы командой.
## Что работает сейчас
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, минимальную React-страницу состояния, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера, /readyz - для готовности ML; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, минимальную React-страницу состояния, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
Это технический каркас. В нем нет регистрации, ролей, профилей, тестов, грейдов, поиска, приглашений, загрузки/анализа резюме, PDF или интеграции с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
@@ -12,7 +12,7 @@
## Целевая система
Один репозиторий, модульный Go backend с Clean Architecture, React SPA на Vite с FSD и отдельный ML HTTP-сервис. Целевой Go-процесс объединяет HTTP API и worker; PostgreSQL хранит бизнес-данные и задания. Резюме и выданные PDF хранятся в закрытом файловом хранилище. Начальная среда - Docker Compose на одном узле приложения и отдельная среда ML.
Один репозиторий, модульный Go backend с Clean Architecture, React SPA на Vite с FSD и отдельный ML HTTP-сервис. Целевой Go-процесс объединяет HTTP API и worker; PostgreSQL хранит бизнес-данные и задания, Redis используется как кеш. Для резюме и выданных PDF выбрано закрытое S3-совместимое хранилище SeaweedFS; сами файловые сценарии пока не реализованы. Начальная среда - Docker Compose на одном узле приложения и отдельная среда ML.
Go владеет авторизацией, подтвержденными категориями, приглашениями, правами на контакты и итоговой выдачей. ML предлагает поля резюме, помогает разобрать потребность работодателя и участвует в экспериментах смыслового поиска. Недоступность модели не должна блокировать ручное заполнение профиля, тестирование, поиск по подтвержденным полям и приглашения.
@@ -42,11 +42,15 @@ Go владеет авторизацией, подтвержденными ка
- bootstrap собирает реализации, запускает процесс и управляет остановкой;
- бизнес-правила остаются в domain/usecase, а не в chi handler, worker, SQL или ML.
Общие настройки Go принадлежат backend/config/ вне internal. Сейчас logkit 0.6.0 и httpkit 0.7.0 из wahrwelt-kit используются для технических функций. Метрики реализованы ограниченным собственным collector/middleware, а pgxpool state не должен блокировать startup. pgkit и httpkit/metrics пока не используются; технические библиотеки не владеют бизнес-логикой. Не добавлять невыбранные JWT, cache или WebSocket зависимости ради предполагаемых будущих сценариев.
Общие настройки Go принадлежат backend/config/ вне internal. Сейчас logkit 0.6.0, httpkit 0.7.0 и cachekit 0.7.0 из wahrwelt-kit используются для технических функций. Метрики реализованы ограниченным собственным collector/middleware, а pgxpool state не должен блокировать startup. pgkit и httpkit/metrics пока не используются; технические библиотеки не владеют бизнес-логикой. Не добавлять невыбранные JWT или WebSocket зависимости ради предполагаемых будущих сценариев.
PostgreSQL с pgx, sqlc и goose остается основной базой. SQL написан вручную, sqlc генерирует типизированный адаптер. goose управляет версионными миграциями. wire в bootstrap - compile-time сборка зависимостей; во время выполнения DI-контейнера нет. Worker и API используют один пул БД в целевом однопроцессном варианте.
Для MVP не вводятся Redis, отдельная vector DB, брокер, Kubernetes или микросервисы поиска. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
Redis входит в основной Compose и подключен через `backend/internal/adapter/secondary/redis/` к outbound-порту кеша. Адаптер предоставляет Get/Set/Del с TTL, а bootstrap управляет подключением и закрытием клиента. Внутренний /readyz требует доступности PostgreSQL, Redis и bucket SeaweedFS. Кеш не является источником истины: вытеснение ключей и перезапуск Redis должны быть допустимы для будущих потребителей. Кеширование профилей, поиска, резюме и другие продуктовые правила еще не реализованы.
SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Загрузка резюме, проверка прав, ограничения содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование.
Для MVP не вводятся отдельная vector DB, брокер, Kubernetes или микросервисы поиска. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
## Структура репозитория и назначение пакетов
@@ -80,7 +84,7 @@ backend/
domain/ плоский пакет; пока только .gitkeep
usecase/health/ operational readiness usecase
port/inbound/ inbound граница readiness
port/outbound/ outbound граница проверки БД
port/outbound/ границы readiness, кеша и объектного хранилища
adapter/primary/http/
api/ generated ogen handler
middleware/ метрики запросов
@@ -89,6 +93,8 @@ backend/
adapter/secondary/
ml/api/ generated client из backend/codegen/ogen-ml.yml
postgres/sqlc/ generated SQL adapter
redis/ адаптер кеша и проверка Redis
seaweedfs/ S3-адаптер и проверка bucket
prometheus/ ограниченные Go/process и request metrics
bootstrap/ конфигурация, wiring, lifecycle, shutdown
db/ миграции и SQL-запросы; продуктовой схемы пока нет
@@ -98,11 +104,11 @@ backend/
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Пока типы не определены, каталог содержит только `.gitkeep`.
`domain/`, продуктовые `usecase/`, адаптеры файлов, почты и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
`domain/`, продуктовые `usecase/`, адаптеры почты и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap и PostgreSQL health query. Аккаунты, резюме, оценивание, приглашения, worker jobs, storage, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap, PostgreSQL health query, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers; `storagepath` нужен только если выбран локальный file storage. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`api/` хранит контракты и инструменты и не является runtime hop в пути запроса. `api/core/` и `api/ml/` владеют исходным OpenAPI, fragments маршрутов и компонентов, а также коммитируемыми bundles. Схемы объединяет корневой `scripts/`. Сгенерированный Go-код лежит у потребителя: публичный handler - в `backend/internal/adapter/primary/http/api/`, внутренний ML client - в `backend/internal/adapter/secondary/ml/api/`, sqlc output - в `backend/internal/adapter/secondary/postgres/sqlc/`. Первый пакет монтируется в chi; два последних реализуют outbound adapters. `backend/cmd/app/main.go` остается точкой входа, а bootstrap отвечает за wiring и graceful shutdown.
@@ -228,9 +234,9 @@ k3s не входит в критический путь. Его можно ра
## Метрики, телеметрия и alerts
Сейчас Go экспортирует стандартные Go/process метрики, `lincodex_http_requests_total` с ограниченными labels `method`, шаблоном маршрута `route` и `status`, а также `lincodex_http_request_duration_seconds`. В labels нельзя помещать user/candidate/request IDs, полный URL, адреса или содержимое резюме. `/metrics` слушает на внутреннем listener и не входит в `/api/v1`. JSON dashboards Go runtime, PostgreSQL и Linux поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики очереди, inference и бизнес-событий пока не реализованы.
Сейчас Go экспортирует стандартные Go/process метрики, `lincodex_http_requests_total` с ограниченными labels `method`, шаблоном маршрута `route` и `status`, а также `lincodex_http_request_duration_seconds`. В labels нельзя помещать user/candidate/request IDs, полный URL, адреса или содержимое резюме. `/metrics` слушает на внутреннем listener и не входит в `/api/v1`. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS и Linux поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики очереди, inference и бизнес-событий пока не реализованы.
План наблюдаемости включает метрики jobs: очередь, возраст старейшего готового задания, время ожидания и выполнения, retries и окончательные ошибки; состояние pgxpool должно собираться внутри Go ограниченными неблокирующими запросами. Nginx `stub_status` не дает latency по HTTP статусам; access logs могут измерять `request_time` и `upstream_response_time`. cAdvisor можно добавить при поддержке выбранного runtime. Redis exporter и DCGM exporter нужны только если появятся Redis или локальная NVIDIA модель.
План наблюдаемости включает метрики jobs: очередь, возраст старейшего готового задания, время ожидания и выполнения, retries и окончательные ошибки; состояние pgxpool должно собираться внутри Go ограниченными неблокирующими запросами. Nginx `stub_status` не дает latency по HTTP статусам; access logs могут измерять `request_time` и `upstream_response_time`. cAdvisor можно добавить при поддержке выбранного runtime. Redis exporter уже включен в отдельный monitoring Compose, Prometheus опрашивает его на внутреннем порту 9121. Метрики SeaweedFS опрашиваются напрямую на внутреннем порту 9327; сохраняются только выбранные агрегированные серии, без путей объектов. DCGM exporter понадобится только при локальной NVIDIA модели.
План браузерного пути: Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. React SDK пока не подключен. Собирать очищенные Web Vitals, JS errors, release и нормализованный маршрут; исключить console logs, формы, текст резюме и session replay. Удалять query string, fragment и ID из URL. Ограничить размер, частоту и origin приемника. Request/trace IDs остаются полями логов, не labels; хранение spans требует отдельного backend, например Tempo, и пока не поддерживается.
+19 -6
View File
@@ -11,13 +11,13 @@
В текущем Compose `POSTGRES_PASSWORD` без URL-кодирования подставляется в `DATABASE_URL`. Используйте пароль из URL-safe символов, например случайную hex-строку. Символы `@`, `/`, `:`, `?`, `#` и `%` пока нельзя вводить в значение без доработки кодирования URI.
Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, backend и Nginx общаются по выделенной Compose сети.
Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Redis, SeaweedFS, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, Redis, SeaweedFS, backend и Nginx общаются по выделенной Compose сети.
Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context.
Для текущего `postgres:alpine` volume монтируется в `/var/lib/postgresql`; образ размещает данные в подкаталоге своей major-версии. При переходе тега на новую major-версию существующую базу нужно мигрировать через `pg_upgrade` или backup/restore. Обновление образа само по себе не преобразует данные.
Откройте http://127.0.0.1:8080. Порт привязан к loopback. Nginx отвечает на /healthz, перенаправляет /api/ в Go и использует SPA fallback для остальных путей. Go health endpoint находится на /api/v1/healthz; Go readiness проверяет PostgreSQL через SELECT 1. Служебный /metrics слушает на внутреннем порту backend 9090.
Откройте http://127.0.0.1:8080. Порт привязан к loopback. Nginx отвечает на /healthz, перенаправляет /api/ в Go и использует SPA fallback для остальных путей. Go health endpoint находится на /api/v1/healthz; внутренний Go /readyz проверяет PostgreSQL через SELECT 1, Redis через PING и bucket SeaweedFS через HeadBucket; недоступность любого из них дает 503. Служебный /metrics слушает на внутреннем порту backend 9090.
Этот Nginx конфиг не настраивает production TLS. Текущий bind не открывает приложение напрямую во внешнюю сеть. Для удаленного доступа требуется отдельно выбранный TLS reverse proxy, firewall и конфигурация целевого окружения.
@@ -29,11 +29,23 @@
make -C deploy down
make -C deploy smoke
Redis использует `redis:alpine`, пароль `REDIS_PASSWORD` из `.env` и внутренний адрес `redis:6379`; порт на хосте не публикуется. Лимит данных - 128 MB с политикой `allkeys-lru`, лимит памяти контейнера - 256 MB. RDB и AOF отключены, постоянного volume нет: кеш очищается при перезапуске. Не храните в нем единственную копию данных. Пароль требуется и backend, и Redis exporter.
Для backend доступны `REDIS_ADDR`, `REDIS_PASSWORD`, `REDIS_DB` и `REDIS_TIMEOUT`. Compose задает адрес `redis:6379`; значения по умолчанию для прямого запуска Go - `localhost:6379`, DB 0 и timeout 1s. Для прямого запуска предоставьте доступный адрес Redis отдельно: текущий Compose не открывает его наружу.
SeaweedFS использует `chrislusf/seaweedfs:latest` и режим `weed mini`: master, volume, filer и S3 API работают в одном контейнере. Именованный volume `seaweedfs_data` смонтирован в `/data` и сохраняет содержимое объектов и метаданные. S3 доступен только внутри сети по `http://seaweedfs:8333`; порт на хосте не публикуется. WebDAV, Admin UI, IAM API, Iceberg и Lance отключены. Nginx продолжает обслуживать frontend и `/api`; прямого маршрута к объектам нет.
Задайте `SEAWEEDFS_ACCESS_KEY` и `SEAWEEDFS_SECRET_KEY` в `.env`, заменив примеры собственными значениями. Compose передает их серверу как `AWS_ACCESS_KEY_ID` и `AWS_SECRET_ACCESS_KEY`, а `SEAWEEDFS_BUCKET` как `S3_BUCKET` для создания bucket при старте. Это одна административная пара для локального стенда, а не разграничение прав production-сервисов. Не передавайте ее браузеру.
Backend использует `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SECRET_KEY`, `SEAWEEDFS_BUCKET`, `SEAWEEDFS_REGION` и `SEAWEEDFS_TIMEOUT`. Compose задает endpoint `http://seaweedfs:8333`; прямой запуск Go по умолчанию использует `http://localhost:8333`, bucket `lincodex`, region `us-east-1` и timeout `10s`. Ключи обязательны. Для прямого запуска нужен отдельно доступный приватный endpoint. Bucket проверяется при readiness; backend не создает его сам.
Обычный `down` сохраняет volume SeaweedFS. Потеря volume означает потерю объектов и метаданных; перед изменением образа или удалением volume нужен проверенный backup. Это один узел без HA, репликации между узлами или настроенного внешнего резервного копирования.
down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова.
## Отдельный ML Compose
ML имеет отдельный Compose-файл и проект. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
make -C deploy ml-config
make -C deploy ml-up
@@ -53,7 +65,7 @@ GET /healthz проверяет процесс. GET /readyz проверяет
Grafana доступна на http://127.0.0.1:3000. Учетные данные берутся из GRAFANA_ADMIN_USER и GRAFANA_ADMIN_PASSWORD в .env. Prometheus, Loki, exporters и backend metrics не публикуют host ports.
Prometheus хранит метрики 14 дней с лимитом 4 GB. Loki хранит логи 7 дней. Alloy discovery отфильтровывает Compose project и принимает логи только backend, frontend и postgres. Разрешенные Loki labels ограничены service и environment; не добавляйте user ID, адреса, resume content, request body или полный URL в labels.
Prometheus хранит метрики 14 дней с лимитом 4 GB. Loki хранит логи 7 дней. Alloy discovery отфильтровывает Compose project и принимает логи только backend, frontend, postgres, redis и seaweedfs. Разрешенные Loki labels ограничены service и environment; не добавляйте user ID, адреса, resume content, request body или полный URL в labels.
Frontend телеметрия пока не подключена в React-приложении. Nginx и Alloy имеют ограниченный /telemetry приемник и конфигурацию Faro, однако UI SDK и сквозная проверка событий отсутствуют.
@@ -70,6 +82,7 @@ Frontend телеметрия пока не подключена в React-при
| Компонент | Текущий источник образа | Основной upstream license |
| --- | --- | --- |
| PostgreSQL | Docker Official Image, docker-library/postgres | PostgreSQL License для сервера; packaging repo MIT |
| SeaweedFS | chrislusf/seaweedfs | [Apache-2.0](https://github.com/seaweedfs/seaweedfs/blob/master/LICENSE) |
| Prometheus | prom/prometheus | Apache-2.0 |
| Loki | grafana/loki | AGPL-3.0-only по умолчанию; см. LICENSING.md исключения |
| Grafana Alloy | grafana/alloy | Apache-2.0 по умолчанию |
@@ -87,9 +100,9 @@ Backend строится с Go 1.26.8; образ runtime выбран в backen
## Observability configuration
Prometheus опрашивает backend /metrics на порту 9090, PostgreSQL exporter, node exporter, себя и необязательный ML target. Loki использует файловое хранилище в single-binary режиме с хранением 168 часов. Grafana загружает datasource Prometheus и Loki из observability/grafana/provisioning/.
Prometheus опрашивает backend /metrics на порту 9090, PostgreSQL exporter, Redis exporter на порту 9121, SeaweedFS на порту 9327, node exporter, себя и необязательный ML target. Loki использует файловое хранилище в single-binary режиме с хранением 168 часов. Grafana загружает datasource Prometheus и Loki из observability/grafana/provisioning/.
Три JSON dashboard в репозитории поддерживаются как панели проекта: Go runtime, PostgreSQL и Linux system. Они не скопированы по Grafana dashboard ID. Для них не заявляется внешнее происхождение или лицензия.
Пять JSON dashboard в репозитории поддерживаются как панели проекта: Go runtime, PostgreSQL, Redis, SeaweedFS и Linux system. Redis dashboard показывает доступность, память, попадания/промахи кеша, вытеснение/истечение ключей и клиентские подключения. Экспортер собирает агрегированные метрики без сканирования ключей. SeaweedFS dashboard показывает доступность, частоту и длительность S3-запросов, ошибки, диск и память; Prometheus сохраняет только выбранные агрегированные метрики без путей объектов. Они не скопированы по Grafana dashboard ID. Для них не заявляется внешнее происхождение или лицензия.
Локальный стек мониторинга рассчитан на разработку и демонстрацию на одном узле и не обеспечивает HA. Проверка Compose валидирует конфигурацию, но не подтверждает production retention, backup вне узла, контроль публичного доступа, доставку alerts или поведение core приложения.
+30 -1
View File
@@ -36,6 +36,8 @@ Orval создает `frontend/src/shared/api/endpoints/` и `schemas/` без
make check не является бизнес-E2E проверкой. make verify запускает deployment smoke с Docker и integration target backend. Для подробностей см. [TESTING.md](TESTING.md); для локального стенда см. [DEPLOY.md](DEPLOY.md).
У инструментов безопасности отдельный цикл установки и проверки: `make -C security install`, затем `make -C security check`. После изменения локальных правил или интеграции сканеров запускайте `make -C security test`; для сборки и сканирования образов сервисов - `make -C security images`. Эти проверки отделены от обычного корневого `make check`; требования, политика и отчеты описаны в [SECURITY.md](SECURITY.md).
## Структура
| Каталог | Назначение |
@@ -49,6 +51,7 @@ make check не является бизнес-E2E проверкой. make verif
| ml/ | Python service, lockfile и генератор Pydantic-моделей |
| deploy/ | Compose, Nginx и smoke |
| observability/ | Prometheus, Loki, Alloy и provisioning/dashboard JSON |
| security/ | Конфигурация сканеров, установка, Make targets и локальные отчеты |
| .agents/ | Канонические проектные инструкции и рабочие стандарты |
| docs/ru/, docs/en/ | Пользовательские документы на русском и английском |
@@ -72,7 +75,11 @@ Go следует границам domain, usecase, port, adapter и bootstrap.
Общие backend параметры находятся в backend/config/. Используются go-logkit 0.6.0 через slog bridge и go-httpkit 0.7.0 для request ID, request logging и panic recovery. Собственный Prometheus middleware сохраняется: он ограничивает method labels и использует chi route patterns; go-httpkit/metrics принимает исходное имя метода как label.
Подключение к PostgreSQL создается через pgxpool.NewWithConfig, а generated SELECT 1 readiness query проверяет доступность БД. Pool constructor не должен ждать доступность БД при startup. go-pgkit 1.4.0 не используется: его constructor проверяет подключение и повторяет попытки до возврата pool, что связывало бы запуск сервиса с доступностью БД. Health handlers остаются явными: helper go-httpkit возвращает ok/degraded и детали проверок, а общий контракт использует ok/ready/not_ready. Не добавляйте pgkit, httpkit/metrics, JWT, cache или WebSocket без конкретной потребности и проверки поведения закрепленной версии.
Подключение к PostgreSQL создается через pgxpool.NewWithConfig, а generated SELECT 1 readiness query проверяет доступность БД. Pool constructor не должен ждать доступность БД при startup. go-pgkit 1.4.0 не используется: его constructor проверяет подключение и повторяет попытки до возврата pool, что связывало бы запуск сервиса с доступностью БД. Health handlers остаются явными: helper go-httpkit возвращает ok/degraded и детали проверок, а общий контракт использует ok/ready/not_ready. Не добавляйте pgkit, httpkit/metrics, JWT или WebSocket без конкретной потребности и проверки поведения закрепленной версии.
Redis подключен через outbound-порт кеша и `backend/internal/adapter/secondary/redis/`. Адаптер использует `go-cachekit` 0.7.0 для операций key/value поверх go-redis; детали библиотек не выходят за его границу. Bootstrap создает клиент без ожидания подключения и закрывает его при завершении; общий /readyz проверяет PostgreSQL, Redis и SeaweedFS. Используйте Get/Set/Del, положительный TTL и отличайте отсутствие ключа от ошибки Redis. Это технический адаптер, потребители продуктового кеша пока не добавлены. Настройки подключения описаны в [DEPLOY.md](DEPLOY.md).
S3-хранилище подключено через outbound-порт `ObjectStorage` и `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS - отдельный сервер, а AWS SDK for Go v2 - клиент Go внутри адаптера. Put/Get передают содержимое потоком; Put требует известный размер в байтах, а вызывающий код обязан закрыть тело, возвращенное Get. Таймаут Get действует до завершения чтения тела. Адаптер ограничивает время операций и отличает отсутствие объекта от ошибки сервиса. Bucket создается при запуске контейнера; Go проверяет его через HeadBucket, не создавая инфраструктуру при обработке запросов. Не добавляйте прямую выдачу приватных файлов Nginx или продуктовые upload/download endpoints без правил доступа.
Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы. Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации.
@@ -80,6 +87,28 @@ ML - отдельный FastAPI процесс. Сейчас он предост
Все комментарии и docstrings в коде пишутся на английском. Инструкции для агентов в корне и .agents также ведутся в единой английской версии; документация команды поддерживается на русском и английском.
## Читаемость Go-кода
- Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.
- Неочевидные лимиты, таймауты, retry settings, границы протоколов и общие значения фикстур получают именованные константы в своем пакете. Размеры вычисляются через `len`, если зависят от данных. Одинаковые числа с разным смыслом получают разные имена. Очевидные нулевые значения, индексы и понятные входы тестов остаются на месте.
- Параметры окружения задаются через config с именованными defaults и валидацией. Значение разбирается один раз; отсутствие переменной отличается от явно заданного неверного значения.
- Функция решает одну понятную задачу. Используйте ранние возвраты, небольшую вложенность и именованные сложные условия. Не добавляйте универсальные helpers, интерфейсы и слои без потребителя.
- Передавайте `context.Context` первым аргументом. Владение ресурсами и зависимости должны быть явными; cleanup регистрируется сразу после создания ресурса, в том числе при частичном startup. Helper не должен скрывать goroutine или глобальное изменяемое состояние.
- Проверяйте ошибки. Неочевидное игнорирование результата объясняйте комментарием. Не сравнивайте тексты ошибок для управления программой и не передавайте внутренние ошибки в HTTP-ответы.
- Комментарии на английском объясняют ограничения и решения. Форматирование выполняют gofmt/goimports. Рефакторинг сохраняет поведение; тесты проверяют существенные границы и крайние случаи, а не названия констант или устройство helpers.
## Формат ошибок
Ошибки в написанном вручную Go-коде имеют формат `Component.Method - operation: %w`, если есть вложенная ошибка, и `Component.Method - reason`, если ее нет. Для обычной функции вместо метода используйте `package.Function`. Например:
```go
if err != nil {
return fmt.Errorf("EmailUseCase.Send - read ctf_name: %w", err)
}
```
Статическая ошибка без причины создается через `errors.New("EmailUseCase.Send - ctf_name is empty")`. Префикс указывает реальный метод, описание пишется на английском без точки в конце. Сохраняйте `errors.Is/As` и идентичность sentinel errors; контекст добавляйте в месте возникновения ошибки. Не добавляйте одинаковые обертки при простом возврате ошибки. Сначала очищайте ошибки внешних SDK от секретов, URL и приватных ключей объектов, затем оборачивайте безопасную причину. Generated code не изменяйте. Логируйте ошибку в месте обработки, а не на каждом уровне.
## Правила изменений
- Проверяйте текущий код и назначенный ownership перед правкой общего файла.
+47
View File
@@ -0,0 +1,47 @@
# Проверки безопасности
В репозитории есть локальные и CI-проверки известных уязвимостей зависимостей, отдельных рисков конфигурации, секретов и опасных конструкций в исходниках. Они относятся к техническому каркасу. Они не подтверждают полную безопасность и не проверяют будущие сценарии авторизации и обработки персональных данных.
## Команды
Запускайте из корня репозитория:
```sh
make -C security install
make -C security check
make -C security test
make -C security images
```
Для установки нужны Python, uv, Go и доступ к сети. Установщик бинарных файлов Trivy/Gitleaks поддерживает Linux amd64 и arm64. Инструменты размещаются в `security/.bin/`, `.tools/` и `.cache/`; глобальные установки не изменяются. Установщик выбирает текущие стабильные версии Trivy и Gitleaks и сверяет скачанные архивы с SHA256-суммами из upstream. govulncheck устанавливается через `go install ...@latest`. Semgrep использует отдельное окружение uv tool с Python 3.13; uv размещает управляемый Python в `security/.tools/python/`. При следующей установке версии могут измениться; для воспроизведения находки сверяйтесь с выводом установки.
| Цель | Область проверки |
| --- | --- |
| `filesystem` | Trivy проверяет зависимости и конфигурацию репозитория по `trivy/filesystem.yml` |
| `secrets` | Gitleaks проверяет текущие файлы и всю доступную историю Git по `gitleaks/gitleaks.toml` |
| `go` | govulncheck анализирует использование известного уязвимого Go-кода в backend |
| `semgrep` | Локальные правила `semgrep/frontend.yml` и `semgrep/python.yml` проверяют исходники frontend и ML |
| `rule-test` | Фикстуры Semgrep проверяют ожидаемые срабатывания и допустимые примеры локальных правил |
| `test` | Запускает фикстуры правил Semgrep и тесты целостности установки, сохранения кода ошибки govulncheck и удаления устаревших отчетов |
| `check` | Запускает проверки файлов, секретов, Go и Semgrep; выполняет каждую и возвращает ошибку, если хотя бы одна не прошла |
| `images` | Собирает образы backend, frontend и ML, затем проверяет каждый точный локальный ID образа через Trivy |
Gitleaks требует полный Git checkout. Отсутствие репозитория или неполная история завершают проверку ошибкой; история не пропускается молча. Значения найденных секретов скрываются в отчетах. Кеши инструментов и результаты сборки исключаются согласно конфигурации; lock-файлы зависимостей приложения остаются входами проверок. Trivy также распознает `requirements-*.txt`, включая `backend/requirements-quality.txt` и `scripts/requirements-codegen.txt`.
Для проверки образов нужен Docker. Контекст сборки backend - `backend/`, frontend и ML - корень репозитория. Образы получают теги `lincodex-security-<service>:local`; перед сканированием определяется ID каждого образа. Команда не запускает контейнеры и не публикует образы. Проверка зависимостей исходников frontend остается необходимой: итоговый Nginx-образ содержит собранные ресурсы, а не дерево зависимостей разработки.
## Находки и исключения
Находки Trivy с уровнем `HIGH` или `CRITICAL` завершают проверку ошибкой, включая уязвимости без опубликованного исправления, если для находки нет действующего адресного исключения. Находки Gitleaks, настроенных правил Semgrep, govulncheck и ошибки самих сканеров также завершают соответствующие цели ошибкой. В конфигурации Go-линтера остается gosec; новые проверки дополняют его.
Перед изменением зависимостей или конфигурации проверьте указанный пакет, установленную версию, затронутый путь и доступное исправление. Отчеты хранятся локально: `security/reports/` исключен из Git. govulncheck использует текстовый вывод, чтобы сохранить собственный код завершения при находках.
В [security/trivy/ignore.yml](../../security/trivy/ignore.yml) есть одно временное исключение, согласованное владельцем проекта 2026-10-05: `CVE-2026-93687` для `pkg:npm/braces@3.0.3` в `frontend/pnpm-lock.yaml`. На момент согласования исправленной версии не было; исключение разблокирует CI зависимостей до истечения срока 2026-10-19. Ответственные - сопровождающие проекта: исключение нужно удалить после появления исправления или пересмотреть до истечения срока. Trivy автоматически учитывает дату окончания. Файл исключений применяется только к проверке файлов; скрытые из блокирующего результата находки остаются видимыми в JSON-отчете. Проверка образов не изменяется.
Любое следующее исключение ограничивайте конкретной находкой и входными данными, указывайте причину, ответственного и срок действия, затем отдавайте изменение на ревью. Текущая интеграция не обеспечивает автоматический контроль срока одинаково для всех инструментов; там, где его нет, проверяйте срок вручную. Не отключайте сканер целиком и не скрывайте все уязвимости без исправлений ради успешной проверки.
## CI и границы проверок
CI запускает `make -C security test check` для исходников и `make -C security images` для образов и включает обе проверки в обязательный общий результат. Отчеты загружаются как artifacts со сроком хранения 14 дней, в том числе при ошибке проверки. Gitleaks скрывает значения секретов, но отчеты могут раскрывать пути репозитория и сведения о зависимостях; доступ к artifacts должен это учитывать.
Локальные правила Semgrep покрывают ограниченный набор случаев для frontend и ML, а не полный аудит приложения. Результаты сканеров зависят от checkout, версий правил, баз уязвимостей, входов сборки и времени запуска. Наличие workflow в репозитории не подтверждает запуск в GitHub или отсутствие находок в текущих файлах. При подготовке релиза фиксируйте фактические результаты; другие границы валидации описаны в [TESTING.md](TESTING.md).
+28 -4
View File
@@ -20,7 +20,7 @@ make test запускает backend, frontend и ML тесты. make check та
| make -C api check | Объединение схем, bundles, OpenAPI lint и тесты merge script |
| make -C backend test | Go unit suite с race detector |
| make -C backend test-fast | Быстрый Go test без race instrumentation |
| make -C backend test-int | Go integration tests с Testcontainers/PostgreSQL |
| make -C backend test-int | Go integration tests с Testcontainers/PostgreSQL/Redis/SeaweedFS |
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries и build |
| make -C ml check | Ruff, mypy, pytest и сборку wheel |
| make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов |
@@ -32,19 +32,43 @@ make -C deploy test-e2e сейчас зарезервирован и завер
make -C ml check-generated использует datamodel-code-generator --check: расхождение завершает проверку ошибкой, а файл моделей остается неизменным. Перед проверкой обновите bundle через make -C api bundle; для обновления Python-моделей используйте make -C ml generate. Сгенерированные модели не подтверждают наличие inference или поддержку всех возможностей OpenAPI 3.2.
Проверки безопасности запускаются отдельно: `make -C security check` проверяет исходники, зависимости и секреты, `make -C security test` проверяет фикстуры локальных правил Semgrep, целостность установки и обработку ошибок govulncheck, `make -C security images` собирает и сканирует образы трех сервисов. Сначала установите инструменты через `make -C security install`. Ошибка сканера означает неуспешную проверку, а не отсутствие находок. Требования к Git/Docker, блокирующие находки и отчеты CI описаны в [SECURITY.md](SECURITY.md).
## Что покрывает текущий каркас
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат.
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат.
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
Deployment smoke проверяет инфраструктурные маршруты и запуск Compose. Он не проверяет получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не проверяет получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
## Bootstrap интеграционных тестов
Общий helper находится в `backend/integration_test/bootstrap_test.go`. Вызов `env := bootstrap(t)` поднимает PostgreSQL, Redis и SeaweedFS, дожидается готовности адаптеров и возвращает окружение с конфигурацией и клиентами. Для проверки одного адаптера используйте `bootstrap(t, postgresService)`, `bootstrap(t, redisService)` или `bootstrap(t, seaweedfsService)`. Можно передать несколько сервисов.
Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой.
Bootstrap поднимает инфраструктуру и клиенты. HTTP-сервер приложения, миграции бизнес-схемы, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS.
## Шардирование интеграционных тестов
`make -C backend test-int` запускает полный набор через `backend/scripts/run-integration-suite.py`. Runner автоматически обнаруживает все верхнеуровневые `Test*` в `./integration_test/...`, сортирует их по пакету и имени, затем распределяет по шардам по кругу. Каждый тест попадает ровно в один шард вместе со всеми своими подтестами. Изменение набора тестов может изменить распределение; балансировка по длительности пока не используется.
```sh
make -C backend test-int-list
TEST_SHARD_INDEX=1 TEST_SHARD_TOTAL=2 make -C backend test-int
TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
```
Индексы начинаются с 1. Обе переменные задаются вместе; неверные параметры, пустой набор, лишние шарды и ошибки обнаружения завершают команду ошибкой. `test-int-list` компилирует тестовый пакет и выводит выбранные тесты без запуска контейнеров. `make -C backend test-scripts` проверяет полное покрытие без пересечений, выбор родительских тестов и передачу ошибок runner. Он входит в `make -C backend check`.
CI запускает отдельную matrix из двух integration jobs с `GOFLAGS=-race` и `fail-fast: false`. Результат всех шардов обязателен для aggregate и deployment smoke. `GOFLAGS='-race -shuffle=on' make -C backend test-int` позволяет локально проверить гонки и независимость порядка. Шарды используют свои контейнеры; общая БД между runner не создается. Число шардов увеличивается в matrix вместе с `TEST_SHARD_TOTAL`, когда длительность suite оправдывает дополнительные runner.
## Будущая программная валидация
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
Общие тестовые данные должны быть изолированы по БД/схеме или сбрасываться последовательно. Не запускайте параллельные сценарии с общим truncate. Контейнер поднимается на suite, порты динамические, cleanup обязателен. Integration job не должен молча пропускать тесты при отсутствии runtime.
Общие тестовые данные должны быть изолированы по БД/схеме или сбрасываться последовательно. Не запускайте параллельные сценарии с общим truncate. Переиспользуйте окружение bootstrap внутри родительского теста; независимые тесты создают свои окружения. Integration job не должен молча пропускать тесты при отсутствии runtime.
Контракты проверяются через bundle, lint, codegen всех Go, TypeScript и Python потребителей и generated drift, включая новые untracked файлы. Frontend component tests не заменяют браузерный тест сквозного пути. После реализации продукта добавить Playwright для двух ролей и явно синтетического кандидата без ФСП.