Перенести актуальную lab2 как базу lab3

This commit is contained in:
Vladislav Agapov
2026-10-16 11:42:02 +03:00
parent 0ab3a341aa
commit a57cbcf329
150 changed files with 10826 additions and 71 deletions
+97
View File
@@ -0,0 +1,97 @@
package main
import (
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/controller"
fiberctrl "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/controller/http/fiber"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/password"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/valkey"
)
const applicationStopTimeout = 9 * time.Second
// CreateApp defines the dependency graph and Fx lifecycle for the lab2 server.
// Constructors do not open sockets; controller.RunControllerFx registers startup
// and shutdown hooks. The outer stop deadline bounds all component cleanup.
func CreateApp() fx.Option {
return fx.Options(
fx.StopTimeout(applicationStopTimeout),
fx.Supply(fx.Annotate(password.Hasher{}, fx.As(new(service.Passwords)))),
fx.Provide(
config.New,
config.NewPersistence,
newDatabase,
newValkey,
newAuthentication,
fx.Annotate(newReadiness, fx.As(new(fiberctrl.Readiness))),
httpConfig,
loggerConfig,
newLogger,
fx.Annotate(newAdmissionLimiter, fx.As(new(admission.Distributed))),
fiberctrl.NewErrorRegistry,
fx.Annotate(databaseStore, fx.As(new(store.Interface))),
fx.Annotate(databaseAccounts, fx.As(new(service.Accounts))),
fx.Annotate(profileCache, fx.As(new(service.ProfileCache))),
fx.Annotate(cursor.New, fx.As(new(service.CursorCodec))),
fx.Annotate(production.NewCached, fx.As(new(service.Service))),
fx.Annotate(fiberctrl.New, fx.As(new(controller.Controller))),
),
fx.WithLogger(newFxLogger),
fx.Invoke(controller.RunControllerFx),
)
}
// httpConfig provides the HTTP configuration section to Fx.
func httpConfig(cfg *config.Config) *config.Controller {
return cfg.HTTP
}
// loggerConfig provides the logging configuration section to Fx.
func loggerConfig(cfg *config.Config) *config.Logger {
return cfg.Logger
}
// newAdmissionLimiter translates configured bounds into separate shared policy budgets.
func newAdmissionLimiter(cfg *config.Controller, client *valkey.Client) (*valkey.Limiter, error) {
global := valkey.Budget{Rate: cfg.Admission.RequestsPerSecond, Slots: cfg.Admission.MaxInFlight}
return valkey.NewLimiter(client, valkey.Limits{
Global: global,
Groups: map[string]valkey.Budget{
"auth": {Rate: cfg.Admission.AuthRate, Slots: cfg.Admission.AuthSlots},
"read": global,
"write": global,
},
User: valkey.Budget{Rate: cfg.Admission.UserRate, Slots: cfg.Admission.UserSlots},
UserGroups: map[string]valkey.Budget{
"auth": {Rate: cfg.Admission.UserAuthRate, Slots: cfg.Admission.UserAuthSlots},
"read": {Rate: cfg.Admission.UserRate, Slots: cfg.Admission.UserSlots},
"write": {Rate: cfg.Admission.UserWriteRate, Slots: cfg.Admission.UserWriteSlots},
},
})
}
// databaseStore exposes business persistence through its consumer interface.
func databaseStore(database *postgres.Store) store.Interface {
return database
}
// databaseAccounts exposes account and session persistence through its consumer interface.
func databaseAccounts(database *postgres.Store) service.Accounts {
return database
}
// profileCache exposes immutable profiles without leaking the Valkey client.
func profileCache(client *valkey.Client) service.ProfileCache {
return client
}
+104
View File
@@ -0,0 +1,104 @@
package main
import (
"context"
"net"
"os"
"testing"
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
)
// TestDependencyGraph ensures constructor signatures and interface bindings agree.
func TestDependencyGraph(t *testing.T) {
if err := fx.ValidateApp(CreateApp(), fx.NopLogger); err != nil {
t.Fatal(err)
}
}
// TestInvalidConfigurationStopsStartup checks failure before a listener is acquired.
func TestInvalidConfigurationStopsStartup(t *testing.T) {
t.Setenv("APP_PORT", "0")
app := fx.New(CreateApp(), fx.NopLogger)
if err := app.Start(context.Background()); err == nil {
t.Fatal("invalid listener configuration accepted")
}
}
// TestCommandValidation ensures unsupported arguments cannot accidentally start a server.
func TestCommandValidation(t *testing.T) {
if err := run([]string{"unknown"}); err == nil {
t.Fatal("unknown command accepted")
}
}
// TestLoggerConfiguration checks that process logging uses its own validated section.
func TestLoggerConfiguration(t *testing.T) {
if _, err := newLogger(&config.Logger{Level: "invalid"}); err == nil {
t.Fatal("invalid logger configuration accepted")
}
}
// TestApplicationLifecycle starts the complete Fx graph and drains its real HTTP listener.
func TestApplicationLifecycle(t *testing.T) {
requirePersistence(t)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
cfg := config.Default()
cfg.HTTP.Host = "127.0.0.1"
cfg.HTTP.Port = listener.Addr().(*net.TCPAddr).Port
cfg.Logger.Level = "error"
if err := listener.Close(); err != nil {
t.Fatal(err)
}
app := fx.New(CreateApp(), fx.Replace(cfg))
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
if err := app.Start(ctx); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer stopCancel()
if err := app.Stop(stopCtx); err != nil {
t.Error(err)
}
})
if err := checkReadiness(cfg.HTTP); err != nil {
t.Fatal(err)
}
}
// TestOccupiedListenerFailsStartup ensures bind failures propagate through the Fx lifecycle.
func TestOccupiedListenerFailsStartup(t *testing.T) {
requirePersistence(t)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() {
_ = listener.Close()
}()
cfg := config.Default()
cfg.HTTP.Host = "127.0.0.1"
cfg.HTTP.Port = listener.Addr().(*net.TCPAddr).Port
cfg.Logger.Level = "error"
app := fx.New(CreateApp(), fx.Replace(cfg), fx.NopLogger)
if err := app.Start(t.Context()); err == nil {
_ = app.Stop(t.Context())
t.Fatal("startup succeeded on an occupied listener")
}
}
// requirePersistence prevents infrastructure scenarios from silently passing on configuration failure.
func requirePersistence(t *testing.T) {
t.Helper()
if os.Getenv("DATABASE_URL") == "" || os.Getenv("VALKEY_SHARDS") == "" {
t.Skip("DATABASE_URL and VALKEY_SHARDS are required for real application lifecycle tests")
}
}
+19
View File
@@ -0,0 +1,19 @@
package main
import (
"fmt"
"go.uber.org/fx"
)
// run dispatches the server command or the container healthcheck.
func run(args []string) error {
if len(args) == 0 {
fx.New(CreateApp()).Run()
return nil
}
if len(args) == 1 && args[0] == "healthcheck" {
return healthcheck()
}
return fmt.Errorf("usage: server [healthcheck]")
}
+46
View File
@@ -0,0 +1,46 @@
package main
import (
"fmt"
"net"
"net/http"
"strconv"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
)
const readinessProbeTimeout = 2 * time.Second
// healthcheck loads configuration and runs the container readiness probe.
func healthcheck() error {
cfg, err := config.New()
if err != nil {
return err
}
return checkReadiness(cfg.HTTP)
}
// checkReadiness checks the local readiness endpoint within the probe timeout.
func checkReadiness(cfg *config.Controller) error {
host := cfg.Host
if host == "0.0.0.0" {
host = "127.0.0.1"
}
if host == "::" {
host = "::1"
}
address := "http://" + net.JoinHostPort(host, strconv.Itoa(cfg.Port)) + "/health/ready"
client := http.Client{Timeout: readinessProbeTimeout}
response, err := client.Get(address)
if err != nil {
return fmt.Errorf("readiness probe: %w", err)
}
defer func() {
_ = response.Body.Close()
}()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("not ready: %d", response.StatusCode)
}
return nil
}
+111
View File
@@ -0,0 +1,111 @@
package main
import (
"errors"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"testing"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
)
// TestRun_Healthcheck verifies command routing to the readiness endpoint.
func TestRun_Healthcheck(t *testing.T) {
// Arrange.
requests := make(chan string, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests <- r.Method + " " + r.URL.Path
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
address := server.Listener.Addr().(*net.TCPAddr)
t.Setenv("APP_HOST", "0.0.0.0")
t.Setenv("APP_PORT", strconv.Itoa(address.Port))
// Act.
err := run([]string{"healthcheck"})
// Assert.
if err != nil {
t.Fatal(err)
}
select {
case got := <-requests:
if got != "GET /health/ready" {
t.Fatalf("probe=%q", got)
}
default:
t.Fatal("command returned success without probing readiness")
}
}
// TestHealthcheck_InvalidConfig rejects invalid startup settings before attempting HTTP.
func TestHealthcheck_InvalidConfig(t *testing.T) {
// Arrange.
t.Setenv("APP_PORT", "invalid")
// Act.
err := healthcheck()
// Assert.
if err == nil {
t.Fatal("invalid port accepted")
}
}
// TestCheckReadiness distinguishes unhealthy responses from connection failures.
func TestCheckReadiness(t *testing.T) {
t.Run("Negative: unhealthy response", func(t *testing.T) {
// Arrange.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
}))
t.Cleanup(server.Close)
address := server.Listener.Addr().(*net.TCPAddr)
cfg := config.Default().HTTP
cfg.Host = "127.0.0.1"
cfg.Port = address.Port
// Act.
err := checkReadiness(cfg)
// Assert.
if err == nil {
t.Fatalf("probe accepted %s", "Negative: unhealthy response")
}
if err.Error() != "not ready: 503" {
t.Fatalf("unexpected health failure: %v", err)
}
})
t.Run("Negative: server unavailable", func(t *testing.T) {
// Arrange.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
}))
t.Cleanup(server.Close)
address := server.Listener.Addr().(*net.TCPAddr)
cfg := config.Default().HTTP
cfg.Host = "127.0.0.1"
cfg.Port = address.Port
server.Close()
// Act.
err := checkReadiness(cfg)
// Assert.
if err == nil {
t.Fatalf("probe accepted %s", "Negative: server unavailable")
}
if _, ok := errors.AsType[*url.Error](err); !ok {
t.Fatalf("connection failure was not preserved: %v", err)
}
})
}
+29
View File
@@ -0,0 +1,29 @@
package main
import (
"go.uber.org/fx/fxevent"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
)
// newLogger creates a structured logger with the configured severity threshold.
func newLogger(cfg *config.Logger) (*zap.Logger, error) {
if err := cfg.Validate(); err != nil {
return nil, err
}
level, err := zapcore.ParseLevel(cfg.Level)
if err != nil {
return nil, err
}
settings := zap.NewProductionConfig()
settings.Level = zap.NewAtomicLevelAt(level)
settings.DisableStacktrace = true
return settings.Build()
}
// newFxLogger adapts the application logger for Fx lifecycle events.
func newFxLogger(log *zap.Logger) fxevent.Logger {
return &fxevent.ZapLogger{Logger: log.Named("fx")}
}
+15
View File
@@ -0,0 +1,15 @@
// Command server runs the messenger or its container readiness probe.
package main
import (
"fmt"
"os"
)
// main runs the selected command and reports failures to stderr.
func main() {
if err := run(os.Args[1:]); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
+77
View File
@@ -0,0 +1,77 @@
package main
import (
"context"
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service/authentication"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store/postgres"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/valkey"
)
type dependencyReadiness struct {
database *postgres.Store
cache *valkey.Client
}
// Ping checks persistence and all limiter shards under a shared deadline.
func (d *dependencyReadiness) Ping(ctx context.Context) error {
if err := d.database.Ping(ctx); err != nil {
return err
}
return d.cache.Ping(ctx)
}
// newDatabase creates the pool and registers its migration/start and shutdown hooks.
func newDatabase(lifecycle fx.Lifecycle, cfg *config.Persistence) (*postgres.Store, error) {
database, err := postgres.New(postgres.Options{
URL: cfg.DatabaseURL,
MaxConnections: int32(cfg.PoolSize),
Timeout: time.Duration(cfg.TimeoutMilliseconds) * time.Millisecond,
})
if err != nil {
return nil, err
}
lifecycle.Append(fx.Hook{
OnStart: database.Start,
OnStop: func(context.Context) error {
database.Close()
return nil
},
})
return database, nil
}
// newValkey creates bounded clients and registers connectivity and cleanup hooks.
func newValkey(lifecycle fx.Lifecycle, cfg *config.Persistence) (*valkey.Client, error) {
client, err := valkey.New(valkey.Options{
Nodes: cfg.Shards,
Coordinator: cfg.Coordinator,
PoolSize: cfg.PoolSize,
Timeout: time.Duration(cfg.TimeoutMilliseconds) * time.Millisecond,
})
if err != nil {
return nil, err
}
lifecycle.Append(fx.Hook{
OnStart: client.Ping,
OnStop: func(context.Context) error {
return client.Close()
},
})
return client, nil
}
// newAuthentication binds credentials and KDF implementations to authentication policy.
func newAuthentication(accounts service.Accounts, passwords service.Passwords, cfg *config.Persistence) (service.Authentication, error) {
return authentication.New(accounts, passwords, time.Duration(cfg.SessionTTLSeconds)*time.Second)
}
// newReadiness assembles infrastructure checks at the composition boundary.
func newReadiness(database *postgres.Store, cache *valkey.Client) *dependencyReadiness {
return &dependencyReadiness{database: database, cache: cache}
}
+48
View File
@@ -0,0 +1,48 @@
package main
import (
"testing"
"time"
"go.uber.org/fx"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store/postgres"
)
// TestDatabaseProviderRejectsInvalidConfiguration verifies dependency errors propagate before startup.
func TestDatabaseProviderRejectsInvalidConfiguration(t *testing.T) {
var lifecycle fx.Lifecycle
app := fx.New(fx.NopLogger, fx.Populate(&lifecycle))
if err := app.Err(); err != nil {
t.Fatal(err)
}
if _, err := newDatabase(lifecycle, &config.Persistence{}); err == nil {
t.Fatal("invalid database settings accepted")
}
}
// TestValkeyProviderRejectsInvalidConfiguration verifies the cache constructor is a real boundary.
func TestValkeyProviderRejectsInvalidConfiguration(t *testing.T) {
var lifecycle fx.Lifecycle
app := fx.New(fx.NopLogger, fx.Populate(&lifecycle))
if err := app.Err(); err != nil {
t.Fatal(err)
}
if _, err := newValkey(lifecycle, &config.Persistence{}); err == nil {
t.Fatal("invalid cache settings accepted")
}
}
// TestReadinessStopsAtUnavailableDatabase checks that mandatory persistence failure is visible.
func TestReadinessStopsAtUnavailableDatabase(t *testing.T) {
database, err := postgres.New(postgres.Options{URL: "postgres://localhost/test", MaxConnections: 1, Timeout: time.Second})
if err != nil {
t.Fatal(err)
}
database.Close()
readiness := newReadiness(database, nil)
if err := readiness.Ping(t.Context()); err == nil {
t.Fatal("closed database reported ready")
}
}