Реализовать lab3 в общем Helm-релизе с Traefik, TLS и HPA

This commit is contained in:
Vladislav Agapov
2026-10-16 11:51:20 +03:00
parent a57cbcf329
commit 9494547300
88 changed files with 1922 additions and 255 deletions
@@ -6,6 +6,7 @@ import (
"sync/atomic"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"go.lab260.ru/fielderr"
"go.uber.org/zap"
@@ -19,6 +20,7 @@ import (
// Its configuration is copied at construction and must not change during serving.
// Fx manages its listener through Start and Stop.
type Controller struct {
metrics *httpMetrics
log *zap.Logger
cfg config.Controller
service service.Service
@@ -28,6 +30,7 @@ type Controller struct {
auth service.Authentication
readiness Readiness
stopping atomic.Bool
instanceID string
serveDone chan error
}
@@ -43,6 +46,7 @@ func New(log *zap.Logger, cfg *config.Controller, svc service.Service, registry
return nil, fmt.Errorf("HTTP logger, service, error registry and admission limiter are required")
}
ctrl := &Controller{
metrics: newHTTPMetrics(),
log: log.Named("controller.http.fiber"),
cfg: *cfg,
service: svc,
@@ -52,6 +56,10 @@ func New(log *zap.Logger, cfg *config.Controller, svc service.Service, registry
readiness: readiness,
serveDone: make(chan error, 1),
}
ctrl.instanceID = cfg.InstanceID
if ctrl.instanceID == "" {
ctrl.instanceID = uuid.NewString()
}
ctrl.configure()
return ctrl, nil
}
@@ -66,6 +66,7 @@ func testController(t *testing.T, change func(*config.Config)) *Controller {
// request sends a raw test request and decodes its response.
func request(ctrl *Controller, method, path, actor string, body []byte) (int, map[string]any, error) {
req := httptest.NewRequest(method, path, bytes.NewReader(body))
req.Header.Set("Idempotency-Key", uuid.NewString())
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
+4 -3
View File
@@ -76,9 +76,10 @@ func (ctrl *Controller) HandleMessagesCreate(ctx *fiber.Ctx) error {
return err
}
message, err := ctrl.service.MessagesCreate(ctx.UserContext(), dto.MessagesCreateRequestDTO{
UserID: identity(ctx),
ChatID: ctx.Params("chat_id"),
Text: request.Text,
IdempotencyKey: ctx.Get("Idempotency-Key"),
UserID: identity(ctx),
ChatID: ctx.Params("chat_id"),
Text: request.Text,
})
if err != nil {
return err
+61
View File
@@ -0,0 +1,61 @@
package fiber
import (
"net/http"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/adaptor"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// httpMetrics owns a per-server registry with bounded labels and no user identifiers.
type httpMetrics struct {
registry *prometheus.Registry
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
active prometheus.Gauge
}
// newHTTPMetrics creates independent collectors so multiple test servers do not share state.
func newHTTPMetrics() *httpMetrics {
metrics := &httpMetrics{
registry: prometheus.NewRegistry(),
requests: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "messenger_http_requests_total", Help: "Completed requests by route, method and status class."}, []string{"route", "method", "status_class"}),
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "messenger_http_duration_seconds", Help: "Completed request latency.", Buckets: prometheus.DefBuckets}, []string{"route", "method"}),
active: prometheus.NewGauge(prometheus.GaugeOpts{Name: "messenger_http_in_flight", Help: "Currently executing HTTP requests."}),
}
metrics.registry.MustRegister(metrics.requests, metrics.duration, metrics.active)
return metrics
}
// observe records bounded route patterns, methods and status classes after error handling.
func (m *httpMetrics) observe(ctx *fiber.Ctx, elapsed time.Duration) {
route := "unmatched"
if ctx.Route() != nil && ctx.Route().Path != "/" {
route = ctx.Route().Path
}
method := ctx.Method()
switch method {
case http.MethodGet, http.MethodPost, http.MethodDelete, http.MethodHead, http.MethodOptions:
default:
method = "other"
}
status := "5xx"
switch ctx.Response().StatusCode() / 100 {
case 2:
status = "2xx"
case 3:
status = "3xx"
case 4:
status = "4xx"
}
m.requests.WithLabelValues(route, method, status).Inc()
m.duration.WithLabelValues(route, method).Observe(elapsed.Seconds())
}
// handleMetrics exposes this process's Prometheus registry without external backend calls.
func (ctrl *Controller) handleMetrics(ctx *fiber.Ctx) error {
return adaptor.HTTPHandler(promhttp.HandlerFor(ctrl.metrics.registry, promhttp.HandlerOpts{}))(ctx)
}
@@ -0,0 +1,73 @@
package fiber
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// TestMetricsEndpoint exposes completed requests without token or user labels.
func TestMetricsEndpoint(t *testing.T) {
ctrl := testController(t, nil)
call(t, ctrl, http.MethodGet, "/health/live", "", nil, http.StatusOK)
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, "/metrics", nil))
if err != nil {
t.Fatal(err)
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), "messenger_http_requests_total") || !strings.Contains(string(body), "messenger_http_duration_seconds_bucket") {
t.Fatalf("invalid metrics response: status %d", resp.StatusCode)
}
if resp.Header.Get("X-Instance-Id") == "" {
t.Fatal("metrics response lacks instance ID")
}
}
// TestInstanceIdentityRemainsStable verifies errors and successes identify the same process.
func TestInstanceIdentityRemainsStable(t *testing.T) {
ctrl := testController(t, nil)
var instance string
for _, path := range []string{"/health/live", "/unknown"} {
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, path, nil))
if err != nil {
t.Fatal(err)
}
if instance == "" {
instance = resp.Header.Get("X-Instance-Id")
}
if instance == "" || resp.Header.Get("X-Instance-Id") != instance {
t.Fatal("unstable instance identity")
}
if err := resp.Body.Close(); err != nil {
t.Fatal(err)
}
}
}
// TestMissingIdempotencyHeader rejects an otherwise valid authenticated write.
func TestMissingIdempotencyHeader(t *testing.T) {
ctrl := testController(t, nil)
caller := user(t, ctrl)
room := chat(t, ctrl, caller)
req := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+room+"/messages", strings.NewReader(`{"text":"valid"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+caller)
resp, err := ctrl.server.Test(req)
if err != nil {
t.Fatal(err)
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("missing key accepted: %d", resp.StatusCode)
}
}
@@ -16,12 +16,18 @@ import (
// request assigns a request identifier, handles errors and logs the completed request.
func (ctrl *Controller) request(ctx *fiber.Ctx) error {
ctx.Set(headerRequestID, uuid.NewString())
ctx.Set("X-Instance-Id", ctrl.instanceID)
started := time.Now()
ctrl.metrics.active.Inc()
defer ctrl.metrics.active.Dec()
err := ctx.Next()
if err != nil {
err = ctrl.handleErr(ctx, err)
}
ctrl.logRequest(ctx, time.Since(started))
if ctx.Path() != "/metrics" {
ctrl.metrics.observe(ctx, time.Since(started))
}
return err
}
+1
View File
@@ -2,6 +2,7 @@ package fiber
// initRoutes registers health endpoints and authenticated application routes.
func (ctrl *Controller) initRoutes() {
ctrl.server.Get("/metrics", ctrl.handleMetrics)
ctrl.server.Get("/health/live", ctrl.handleLive)
ctrl.server.Get("/health/ready", ctrl.handleReady)
ctrl.server.Use(ctrl.admit)