Перенести актуальную lab2 как базу lab3
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
package admission
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ErrRate means the request exhausted a shared rate budget.
|
||||
var ErrRate = errors.New("shared request rate exceeded")
|
||||
|
||||
// ErrSlots means the request exhausted a shared concurrency budget.
|
||||
var ErrSlots = errors.New("shared execution slots exhausted")
|
||||
|
||||
// Distributed defines request admission independently of the backing database.
|
||||
type Distributed interface {
|
||||
// Enter reserves global/group or user/group budgets and returns a release operation.
|
||||
Enter(ctx context.Context, group, user string) (func(), error)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Package admission bounds request rate and concurrent execution independently of transport.
|
||||
package admission
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Options defines the rate and execution bounds for one limiter.
|
||||
type Options struct {
|
||||
// MaxInFlight limits concurrent executions without an admission queue.
|
||||
MaxInFlight int
|
||||
// RequestsPerSecond is the token refill rate.
|
||||
RequestsPerSecond int
|
||||
// Burst is the maximum number of immediately available tokens.
|
||||
Burst int
|
||||
}
|
||||
|
||||
// Limiter owns synchronization for the token bucket and execution slots.
|
||||
// It knows neither HTTP response codes nor application shutdown state.
|
||||
type Limiter struct {
|
||||
mu sync.Mutex
|
||||
rate float64
|
||||
burst float64
|
||||
tokens float64
|
||||
lastRefill time.Time
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
// New validates limits and creates a full token bucket with bounded execution slots.
|
||||
func New(cfg Options) (*Limiter, error) {
|
||||
if cfg.MaxInFlight <= 0 || cfg.RequestsPerSecond <= 0 || cfg.Burst <= 0 {
|
||||
return nil, fmt.Errorf("admission limits must be positive")
|
||||
}
|
||||
return &Limiter{
|
||||
rate: float64(cfg.RequestsPerSecond),
|
||||
burst: float64(cfg.Burst),
|
||||
tokens: float64(cfg.Burst),
|
||||
lastRefill: time.Now(),
|
||||
slots: make(chan struct{}, cfg.MaxInFlight),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Allow refills the token bucket and consumes a token when one is available.
|
||||
func (limiter *Limiter) Allow(now time.Time) bool {
|
||||
limiter.mu.Lock()
|
||||
defer limiter.mu.Unlock()
|
||||
elapsed := max(0, now.Sub(limiter.lastRefill).Seconds())
|
||||
limiter.tokens = min(limiter.burst, limiter.tokens+elapsed*limiter.rate)
|
||||
limiter.lastRefill = now
|
||||
if limiter.tokens < 1 {
|
||||
return false
|
||||
}
|
||||
limiter.tokens--
|
||||
return true
|
||||
}
|
||||
|
||||
// Acquire reserves an execution slot without waiting.
|
||||
func (limiter *Limiter) Acquire() bool {
|
||||
select {
|
||||
case limiter.slots <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Release returns an execution slot previously reserved by Acquire.
|
||||
// Each successful Acquire must be paired with exactly one Release.
|
||||
func (limiter *Limiter) Release() {
|
||||
<-limiter.slots
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package admission
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestLimiter_Allow checks token exhaustion and refill with deterministic time.
|
||||
func TestLimiter_Allow(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
elapsed time.Duration
|
||||
want bool
|
||||
}{
|
||||
{"Negative: exhausted bucket", 0, false},
|
||||
{"Negative: partial token", time.Millisecond * 500, false},
|
||||
{"Positive: refilled token", time.Second, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
// Arrange.
|
||||
limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1})
|
||||
if !limiter.Allow(time.Now()) {
|
||||
t.Fatal("fixture token missing")
|
||||
}
|
||||
time.Sleep(tc.elapsed)
|
||||
|
||||
// Act.
|
||||
got := limiter.Allow(time.Now())
|
||||
|
||||
// Assert.
|
||||
if got != tc.want {
|
||||
t.Fatalf("Allow after %s=%v, want=%v", tc.elapsed, got, tc.want)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLimiter_Acquire checks available, occupied and released execution slots independently.
|
||||
func TestLimiter_Acquire(t *testing.T) {
|
||||
t.Run("Positive: free slot", func(t *testing.T) {
|
||||
// Arrange.
|
||||
limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1})
|
||||
|
||||
want := true
|
||||
|
||||
// Act.
|
||||
got := limiter.Acquire()
|
||||
if got {
|
||||
t.Cleanup(limiter.Release)
|
||||
}
|
||||
|
||||
// Assert.
|
||||
if got != want {
|
||||
t.Fatalf("Acquire=%v, want=%v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: occupied slot", func(t *testing.T) {
|
||||
// Arrange.
|
||||
limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1})
|
||||
|
||||
if !limiter.Acquire() {
|
||||
t.Fatal("fixture slot unavailable")
|
||||
}
|
||||
|
||||
t.Cleanup(limiter.Release)
|
||||
|
||||
want := false
|
||||
|
||||
// Act.
|
||||
got := limiter.Acquire()
|
||||
if got {
|
||||
t.Cleanup(limiter.Release)
|
||||
}
|
||||
|
||||
// Assert.
|
||||
if got != want {
|
||||
t.Fatalf("Acquire=%v, want=%v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Positive: released slot", func(t *testing.T) {
|
||||
// Arrange.
|
||||
limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1})
|
||||
|
||||
if !limiter.Acquire() {
|
||||
t.Fatal("fixture slot unavailable")
|
||||
}
|
||||
|
||||
limiter.Release()
|
||||
|
||||
want := true
|
||||
|
||||
// Act.
|
||||
got := limiter.Acquire()
|
||||
if got {
|
||||
t.Cleanup(limiter.Release)
|
||||
}
|
||||
|
||||
// Assert.
|
||||
if got != want {
|
||||
t.Fatalf("Acquire=%v, want=%v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// newTestLimiter creates a limiter or fails the test on invalid settings.
|
||||
func newTestLimiter(t *testing.T, options Options) *Limiter {
|
||||
t.Helper()
|
||||
limiter, err := New(options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return limiter
|
||||
}
|
||||
|
||||
// TestLimiter_New rejects each nonpositive limit independently.
|
||||
func TestLimiter_New(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
options Options
|
||||
}{
|
||||
{"Negative: zero concurrency", Options{MaxInFlight: 0, RequestsPerSecond: 1, Burst: 1}},
|
||||
{"Negative: negative concurrency", Options{MaxInFlight: -1, RequestsPerSecond: 1, Burst: 1}},
|
||||
{"Negative: zero refill rate", Options{MaxInFlight: 1, RequestsPerSecond: 0, Burst: 1}},
|
||||
{"Negative: negative refill rate", Options{MaxInFlight: 1, RequestsPerSecond: -1, Burst: 1}},
|
||||
{"Negative: zero burst", Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 0}},
|
||||
{"Negative: negative burst", Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: -1}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
options := tc.options
|
||||
|
||||
// Act.
|
||||
limiter, err := New(options)
|
||||
|
||||
// Assert.
|
||||
if err == nil || limiter != nil {
|
||||
t.Fatalf("invalid options accepted: %v, %v", limiter, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Package config loads and validates the environment configuration of the application.
|
||||
package config
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Config groups settings by the component that consumes them.
|
||||
type Config struct {
|
||||
// HTTP configures the listener, request limits and shutdown deadline.
|
||||
HTTP *Controller
|
||||
// Memory configures the capacity of the process-local store.
|
||||
Memory *Memory
|
||||
// Logger configures structured process logging.
|
||||
Logger *Logger
|
||||
}
|
||||
|
||||
// Default returns independent configuration sections with the documented defaults.
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
HTTP: defaultController(),
|
||||
Memory: defaultMemory(),
|
||||
Logger: &Logger{Level: "info"},
|
||||
}
|
||||
}
|
||||
|
||||
// New loads environment overrides and rejects invalid settings before startup.
|
||||
func New() (*Config, error) {
|
||||
cfg := Default()
|
||||
if err := cfg.HTTP.loadEnvironment(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.Memory.loadEnvironment(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.Logger.loadEnvironment()
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Validate verifies the presence and invariants of each configuration section.
|
||||
func (cfg *Config) Validate() error {
|
||||
if cfg == nil || cfg.HTTP == nil || cfg.Memory == nil || cfg.Logger == nil {
|
||||
return fmt.Errorf("HTTP, Memory and Logger configuration sections are required")
|
||||
}
|
||||
if err := cfg.HTTP.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cfg.Memory.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return cfg.Logger.Validate()
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestConfig_New checks individual environment overrides and invalid settings.
|
||||
func TestConfig_New(t *testing.T) {
|
||||
t.Run("Positive: APP_PORT override", func(t *testing.T) {
|
||||
// Arrange.
|
||||
t.Setenv("APP_PORT", "18080")
|
||||
|
||||
// Act.
|
||||
cfg, err := New()
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.HTTP.Port != 18080 {
|
||||
t.Fatalf("APP_PORT=%v, want=%v", cfg.HTTP.Port, 18080)
|
||||
}
|
||||
})
|
||||
t.Run("Positive: REQUEST_TIMEOUT_SECONDS override", func(t *testing.T) {
|
||||
// Arrange.
|
||||
t.Setenv("REQUEST_TIMEOUT_SECONDS", "4")
|
||||
|
||||
// Act.
|
||||
cfg, err := New()
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.HTTP.TimeoutSeconds != 4 {
|
||||
t.Fatalf("REQUEST_TIMEOUT_SECONDS=%v, want=%v", cfg.HTTP.TimeoutSeconds, 4)
|
||||
}
|
||||
})
|
||||
t.Run("Positive: MAX_MESSAGES override", func(t *testing.T) {
|
||||
// Arrange.
|
||||
t.Setenv("MAX_MESSAGES", "25")
|
||||
|
||||
// Act.
|
||||
cfg, err := New()
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Memory.MaxMessages != 25 {
|
||||
t.Fatalf("MAX_MESSAGES=%v, want=%v", cfg.Memory.MaxMessages, 25)
|
||||
}
|
||||
})
|
||||
t.Run("Positive: REQUESTS_PER_SECOND override", func(t *testing.T) {
|
||||
// Arrange.
|
||||
t.Setenv("REQUESTS_PER_SECOND", "12")
|
||||
|
||||
// Act.
|
||||
cfg, err := New()
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.HTTP.Admission.RequestsPerSecond != 12 {
|
||||
t.Fatalf("REQUESTS_PER_SECOND=%v, want=%v", cfg.HTTP.Admission.RequestsPerSecond, 12)
|
||||
}
|
||||
})
|
||||
t.Run("Positive: LOG_LEVEL override", func(t *testing.T) {
|
||||
// Arrange.
|
||||
t.Setenv("LOG_LEVEL", "debug")
|
||||
|
||||
// Act.
|
||||
cfg, err := New()
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Logger.Level != "debug" {
|
||||
t.Fatalf("LOG_LEVEL=%v, want=%v", cfg.Logger.Level, "debug")
|
||||
}
|
||||
})
|
||||
cases := []struct {
|
||||
name string
|
||||
key string
|
||||
value string
|
||||
}{
|
||||
{"port exceeds TCP range", "APP_PORT", "65536"},
|
||||
{"zero message capacity", "MAX_MESSAGES", "0"},
|
||||
{"nonnumeric body limit", "MAX_BODY_BYTES", "bad"},
|
||||
{"shutdown deadline exceeds bound", "SHUTDOWN_TIMEOUT_SECONDS", "10"},
|
||||
{"hostname instead of bind IP", "APP_HOST", "hostname"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run("Negative: "+tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
t.Setenv(tc.key, tc.value)
|
||||
|
||||
// Act.
|
||||
cfg, err := New()
|
||||
|
||||
// Assert.
|
||||
if err == nil || cfg != nil {
|
||||
t.Fatalf("invalid %s=%q returned config=%+v, error=%v", tc.key, tc.value, cfg, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfig_Validate rejects one missing section or invalid component per scenario.
|
||||
func TestConfig_Validate(t *testing.T) {
|
||||
t.Run("Negative: nil config", func(t *testing.T) {
|
||||
// Arrange.
|
||||
var cfg *Config
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatalf("accepted %s", "nil config")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing HTTP", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := Default()
|
||||
|
||||
cfg.HTTP = nil
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatalf("accepted %s", "missing HTTP")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing Memory", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := Default()
|
||||
|
||||
cfg.Memory = nil
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatalf("accepted %s", "missing Memory")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing Logger", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := Default()
|
||||
|
||||
cfg.Logger = nil
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatalf("accepted %s", "missing Logger")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown log level", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := Default()
|
||||
|
||||
cfg.Logger.Level = "unknown"
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatalf("accepted %s", "unknown log level")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: zero storage capacity", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := Default()
|
||||
|
||||
cfg.Memory.MaxUsers = 0
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatalf("accepted %s", "zero storage capacity")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: zero concurrency", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := Default()
|
||||
|
||||
cfg.HTTP.Admission.MaxInFlight = 0
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatalf("accepted %s", "zero concurrency")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestLogger_Validate rejects an absent logging section without panicking.
|
||||
func TestLogger_Validate(t *testing.T) {
|
||||
// Arrange.
|
||||
var cfg *Logger
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatal("nil logger accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMemory_Validate rejects absent storage settings without panicking.
|
||||
func TestMemory_Validate(t *testing.T) {
|
||||
// Arrange.
|
||||
var cfg *Memory
|
||||
|
||||
// Act.
|
||||
err := cfg.Validate()
|
||||
|
||||
// Assert.
|
||||
if err == nil {
|
||||
t.Fatal("nil memory configuration accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
maxTCPPort = 65535
|
||||
maxShutdownTimeoutSeconds = 9
|
||||
maxRequestTimeoutSeconds = 15
|
||||
)
|
||||
|
||||
// Controller contains settings owned exclusively by the HTTP transport.
|
||||
type Controller struct {
|
||||
// Host is the IP address on which the listener binds.
|
||||
Host string
|
||||
// Port is the TCP port, in the range 1..65535.
|
||||
Port int
|
||||
// TimeoutSeconds limits request reads, response writes and idle connections.
|
||||
TimeoutSeconds int
|
||||
// ShutdownTimeoutSeconds bounds draining of active requests; it must not exceed nine seconds.
|
||||
ShutdownTimeoutSeconds int
|
||||
// MaxBodyBytes is the maximum accepted request body size before decoding.
|
||||
MaxBodyBytes int
|
||||
// MaxConnections bounds simultaneous connections handled by fasthttp.
|
||||
MaxConnections int
|
||||
// Admission controls business request throughput and execution concurrency.
|
||||
Admission Admission
|
||||
}
|
||||
|
||||
// Admission defines shared request policies; health endpoints bypass them.
|
||||
type Admission struct {
|
||||
// MaxInFlight is the maximum number of executing requests, with no waiting queue.
|
||||
MaxInFlight int
|
||||
// RequestsPerSecond is the token refill rate for the global admission bucket.
|
||||
RequestsPerSecond int
|
||||
// Burst is the bucket capacity and maximum immediate request burst.
|
||||
Burst int
|
||||
// AuthRate limits public registration/login attempts per second.
|
||||
AuthRate int
|
||||
// AuthSlots bounds concurrent password KDF work globally.
|
||||
AuthSlots int
|
||||
// UserRate limits each authenticated account across all groups.
|
||||
UserRate int
|
||||
// UserSlots bounds concurrency across one account's groups.
|
||||
UserSlots int
|
||||
// UserWriteRate limits one account's write attempts per second.
|
||||
UserWriteRate int
|
||||
// UserWriteSlots bounds one account's concurrent writes.
|
||||
UserWriteSlots int
|
||||
// UserAuthRate limits session-management operations per account.
|
||||
UserAuthRate int
|
||||
// UserAuthSlots bounds one account's session-management concurrency.
|
||||
UserAuthSlots int
|
||||
}
|
||||
|
||||
// defaultController returns the default listener, timeout and admission settings.
|
||||
func defaultController() *Controller {
|
||||
return &Controller{
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
TimeoutSeconds: 3,
|
||||
ShutdownTimeoutSeconds: 5,
|
||||
MaxBodyBytes: 64 << 10,
|
||||
MaxConnections: 256,
|
||||
Admission: Admission{
|
||||
MaxInFlight: 32,
|
||||
RequestsPerSecond: 1000,
|
||||
Burst: 100,
|
||||
AuthRate: 100,
|
||||
AuthSlots: 4,
|
||||
UserRate: 100,
|
||||
UserSlots: 8,
|
||||
UserWriteRate: 50,
|
||||
UserWriteSlots: 4,
|
||||
UserAuthRate: 20,
|
||||
UserAuthSlots: 2,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// loadEnvironment applies environment overrides to this configuration section.
|
||||
func (cfg *Controller) loadEnvironment() error {
|
||||
if host, exists := os.LookupEnv("APP_HOST"); exists {
|
||||
cfg.Host = host
|
||||
}
|
||||
return loadIntegers(
|
||||
integerSetting{"APP_PORT", &cfg.Port},
|
||||
integerSetting{"REQUEST_TIMEOUT_SECONDS", &cfg.TimeoutSeconds},
|
||||
integerSetting{"SHUTDOWN_TIMEOUT_SECONDS", &cfg.ShutdownTimeoutSeconds},
|
||||
integerSetting{"MAX_BODY_BYTES", &cfg.MaxBodyBytes},
|
||||
integerSetting{"MAX_CONNECTIONS", &cfg.MaxConnections},
|
||||
integerSetting{"MAX_IN_FLIGHT", &cfg.Admission.MaxInFlight},
|
||||
integerSetting{"REQUESTS_PER_SECOND", &cfg.Admission.RequestsPerSecond},
|
||||
integerSetting{"REQUEST_BURST", &cfg.Admission.Burst},
|
||||
integerSetting{"AUTH_RATE", &cfg.Admission.AuthRate},
|
||||
integerSetting{"AUTH_SLOTS", &cfg.Admission.AuthSlots},
|
||||
integerSetting{"USER_RATE", &cfg.Admission.UserRate},
|
||||
integerSetting{"USER_SLOTS", &cfg.Admission.UserSlots},
|
||||
integerSetting{"USER_WRITE_RATE", &cfg.Admission.UserWriteRate},
|
||||
integerSetting{"USER_WRITE_SLOTS", &cfg.Admission.UserWriteSlots},
|
||||
integerSetting{"USER_AUTH_RATE", &cfg.Admission.UserAuthRate},
|
||||
integerSetting{"USER_AUTH_SLOTS", &cfg.Admission.UserAuthSlots},
|
||||
)
|
||||
}
|
||||
|
||||
// Validate checks listener addresses, timeouts and admission bounds.
|
||||
func (cfg *Controller) Validate() error {
|
||||
if cfg == nil {
|
||||
return fmt.Errorf("HTTP configuration is required")
|
||||
}
|
||||
if cfg.TimeoutSeconds > maxRequestTimeoutSeconds {
|
||||
return fmt.Errorf("REQUEST_TIMEOUT_SECONDS must not exceed %d", maxRequestTimeoutSeconds)
|
||||
}
|
||||
if net.ParseIP(cfg.Host) == nil {
|
||||
return fmt.Errorf("APP_HOST must be an IP address")
|
||||
}
|
||||
if cfg.Port < 1 || cfg.Port > maxTCPPort {
|
||||
return fmt.Errorf("APP_PORT must be 1..%d", maxTCPPort)
|
||||
}
|
||||
if cfg.ShutdownTimeoutSeconds < 1 || cfg.ShutdownTimeoutSeconds > maxShutdownTimeoutSeconds {
|
||||
return fmt.Errorf("SHUTDOWN_TIMEOUT_SECONDS must be 1..%d", maxShutdownTimeoutSeconds)
|
||||
}
|
||||
settings := []integerSetting{
|
||||
{"REQUEST_TIMEOUT_SECONDS", &cfg.TimeoutSeconds},
|
||||
{"MAX_BODY_BYTES", &cfg.MaxBodyBytes},
|
||||
{"MAX_CONNECTIONS", &cfg.MaxConnections},
|
||||
{"MAX_IN_FLIGHT", &cfg.Admission.MaxInFlight},
|
||||
{"REQUESTS_PER_SECOND", &cfg.Admission.RequestsPerSecond},
|
||||
{"REQUEST_BURST", &cfg.Admission.Burst},
|
||||
}
|
||||
for _, setting := range settings {
|
||||
if err := validatePositive(setting.name, *setting.target); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Bind returns the listener address, including brackets for IPv6 hosts.
|
||||
func (cfg *Controller) Bind() string {
|
||||
return net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
|
||||
}
|
||||
|
||||
// Timeout returns the configured read, write and idle timeout.
|
||||
func (cfg *Controller) Timeout() time.Duration {
|
||||
return time.Duration(cfg.TimeoutSeconds) * time.Second
|
||||
}
|
||||
|
||||
// ShutdownTimeout returns the maximum time allowed to drain active requests.
|
||||
func (cfg *Controller) ShutdownTimeout() time.Duration {
|
||||
return time.Duration(cfg.ShutdownTimeoutSeconds) * time.Second
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const maxConfiguredInteger = 1 << 30
|
||||
|
||||
type integerSetting struct {
|
||||
name string
|
||||
target *int
|
||||
}
|
||||
|
||||
// loadIntegers parses configured integer overrides and reports invalid values.
|
||||
func loadIntegers(settings ...integerSetting) error {
|
||||
for _, setting := range settings {
|
||||
raw, exists := os.LookupEnv(setting.name)
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
value, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s must be an integer", setting.name)
|
||||
}
|
||||
if err := validatePositive(setting.name, value); err != nil {
|
||||
return err
|
||||
}
|
||||
*setting.target = value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validatePositive checks that a setting is positive and within the supported range.
|
||||
func validatePositive(name string, value int) error {
|
||||
if value < 1 || value > maxConfiguredInteger {
|
||||
return fmt.Errorf("%s must be between 1 and %d", name, maxConfiguredInteger)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Logger configures the minimum severity written as structured JSON to stderr.
|
||||
type Logger struct {
|
||||
// Level is one of debug, info, warn or error; the default is info.
|
||||
Level string
|
||||
}
|
||||
|
||||
// loadEnvironment applies environment overrides to this configuration section.
|
||||
func (cfg *Logger) loadEnvironment() {
|
||||
if level, exists := os.LookupEnv("LOG_LEVEL"); exists {
|
||||
cfg.Level = level
|
||||
}
|
||||
}
|
||||
|
||||
// Validate rejects unsupported levels rather than silently changing verbosity.
|
||||
func (cfg *Logger) Validate() error {
|
||||
if cfg == nil {
|
||||
return fmt.Errorf("Logger configuration is required")
|
||||
}
|
||||
switch cfg.Level {
|
||||
case "debug", "info", "warn", "error":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("LOG_LEVEL must be debug, info, warn or error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package config
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Memory defines logical capacity limits; MaxStateBytes is not a measurement of RSS.
|
||||
type Memory struct {
|
||||
// MaxUsers limits the number of registered users.
|
||||
MaxUsers int
|
||||
// MaxChats limits the number of immutable chats.
|
||||
MaxChats int
|
||||
// MaxMessages limits the total number of messages across all chats.
|
||||
MaxMessages int
|
||||
// MaxStateBytes limits the logical storage budget, including estimated record overhead.
|
||||
MaxStateBytes int
|
||||
}
|
||||
|
||||
// defaultMemory returns the default storage capacity limits.
|
||||
func defaultMemory() *Memory {
|
||||
return &Memory{
|
||||
MaxUsers: 10000,
|
||||
MaxChats: 10000,
|
||||
MaxMessages: 100000,
|
||||
MaxStateBytes: 32 << 20,
|
||||
}
|
||||
}
|
||||
|
||||
// loadEnvironment applies environment overrides to this configuration section.
|
||||
func (cfg *Memory) loadEnvironment() error {
|
||||
return loadIntegers(
|
||||
integerSetting{"MAX_USERS", &cfg.MaxUsers},
|
||||
integerSetting{"MAX_CHATS", &cfg.MaxChats},
|
||||
integerSetting{"MAX_MESSAGES", &cfg.MaxMessages},
|
||||
integerSetting{"MAX_STATE_BYTES", &cfg.MaxStateBytes},
|
||||
)
|
||||
}
|
||||
|
||||
// Validate rejects disabled, negative and excessively large storage limits.
|
||||
func (cfg *Memory) Validate() error {
|
||||
if cfg == nil {
|
||||
return fmt.Errorf("Memory configuration is required")
|
||||
}
|
||||
settings := []integerSetting{
|
||||
{"MAX_USERS", &cfg.MaxUsers},
|
||||
{"MAX_CHATS", &cfg.MaxChats},
|
||||
{"MAX_MESSAGES", &cfg.MaxMessages},
|
||||
{"MAX_STATE_BYTES", &cfg.MaxStateBytes},
|
||||
}
|
||||
for _, setting := range settings {
|
||||
if err := validatePositive(setting.name, *setting.target); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Persistence contains database, cache and session settings.
|
||||
type Persistence struct {
|
||||
// DatabaseURL identifies the PostgreSQL database.
|
||||
DatabaseURL string
|
||||
// Shards maps stable identities to Valkey addresses.
|
||||
Shards map[string]string
|
||||
// Coordinator names the stable global admission shard.
|
||||
Coordinator string
|
||||
// PoolSize bounds connections per dependency.
|
||||
PoolSize int
|
||||
// TimeoutMilliseconds bounds each dependency operation.
|
||||
TimeoutMilliseconds int
|
||||
// SessionTTLSeconds sets the absolute session lifetime.
|
||||
SessionTTLSeconds int
|
||||
}
|
||||
|
||||
// NewPersistence loads dependency settings separately from HTTP configuration.
|
||||
func NewPersistence() (*Persistence, error) {
|
||||
cfg := &Persistence{
|
||||
DatabaseURL: os.Getenv("DATABASE_URL"),
|
||||
Coordinator: os.Getenv("VALKEY_COORDINATOR"),
|
||||
Shards: make(map[string]string),
|
||||
PoolSize: 8,
|
||||
TimeoutMilliseconds: 1000,
|
||||
SessionTTLSeconds: 3600,
|
||||
}
|
||||
if cfg.Coordinator == "" {
|
||||
cfg.Coordinator = "shard0"
|
||||
}
|
||||
for _, entry := range strings.Split(os.Getenv("VALKEY_SHARDS"), ",") {
|
||||
id, address, ok := strings.Cut(entry, "=")
|
||||
if !ok || id == "" || address == "" || cfg.Shards[id] != "" {
|
||||
return nil, fmt.Errorf("VALKEY_SHARDS requires unique id=address entries")
|
||||
}
|
||||
cfg.Shards[id] = address
|
||||
}
|
||||
if cfg.DatabaseURL == "" || cfg.Shards[cfg.Coordinator] == "" {
|
||||
return nil, fmt.Errorf("DATABASE_URL and a configured VALKEY_COORDINATOR are required")
|
||||
}
|
||||
if err := loadIntegers(integerSetting{"DEPENDENCY_POOL_SIZE", &cfg.PoolSize}, integerSetting{"DEPENDENCY_TIMEOUT_MS", &cfg.TimeoutMilliseconds}, integerSetting{"SESSION_TTL_SECONDS", &cfg.SessionTTLSeconds}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestPersistenceConfiguration validates independent environment configurations.
|
||||
func TestPersistenceConfiguration(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
database string
|
||||
shards string
|
||||
coordinator string
|
||||
ttl string
|
||||
valid bool
|
||||
}{
|
||||
{"defaults", "postgres://localhost/test", "shard0=localhost:6379", "", "3600", true},
|
||||
{"missing database", "", "shard0=localhost:6379", "", "3600", false},
|
||||
{"missing coordinator", "postgres://localhost/test", "shard1=localhost:6379", "shard0", "3600", false},
|
||||
{"duplicate shard", "postgres://localhost/test", "shard0=a,shard0=b", "", "3600", false},
|
||||
{"invalid topology", "postgres://localhost/test", "wrong", "", "3600", false},
|
||||
{"invalid ttl", "postgres://localhost/test", "shard0=a", "", "no", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv("DATABASE_URL", tc.database)
|
||||
t.Setenv("VALKEY_SHARDS", tc.shards)
|
||||
t.Setenv("VALKEY_COORDINATOR", tc.coordinator)
|
||||
t.Setenv("SESSION_TTL_SECONDS", tc.ttl)
|
||||
_, err := NewPersistence()
|
||||
if (err == nil) != tc.valid {
|
||||
t.Fatalf("unexpected validation result: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package controller
|
||||
|
||||
import "go.uber.org/fx"
|
||||
|
||||
// RunControllerFx lets Fx own startup, signal handling and graceful shutdown.
|
||||
func RunControllerFx(lc fx.Lifecycle, ctrl Controller) {
|
||||
lc.Append(fx.Hook{OnStart: ctrl.Start, OnStop: ctrl.Stop})
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
const identityKey = "authenticated-user"
|
||||
|
||||
// HandleLogin structurally decodes Basic credentials and delegates authentication.
|
||||
func (ctrl *Controller) HandleLogin(ctx *fiber.Ctx) error {
|
||||
scheme, encoded, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Basic") {
|
||||
return service.ErrUnauthorized
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return service.ErrUnauthorized
|
||||
}
|
||||
username, password, ok := strings.Cut(string(decoded), ":")
|
||||
if !ok {
|
||||
return service.ErrUnauthorized
|
||||
}
|
||||
if len(ctx.Body()) != 0 {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
session, err := ctrl.auth.Login(ctx.UserContext(), username, password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusCreated).JSON(fiber.Map{
|
||||
"token": session.Token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session.ExpiresAt,
|
||||
"user": userResponse(session.User),
|
||||
})
|
||||
}
|
||||
|
||||
// HandleLogout revokes the current authenticated token before returning no content.
|
||||
func (ctrl *Controller) HandleLogout(ctx *fiber.Ctx) error {
|
||||
if err := ctrl.auth.Logout(ctx.UserContext(), bearer(ctx)); err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.SendStatus(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// bearer extracts a Bearer token without interpreting its identity or validity.
|
||||
func bearer(ctx *fiber.Ctx) string {
|
||||
scheme, token, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return ""
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
// identity reads only the identity produced by successful session authentication.
|
||||
func identity(ctx *fiber.Ctx) string {
|
||||
value, _ := ctx.Locals(identityKey).(string)
|
||||
return value
|
||||
}
|
||||
|
||||
// requestGroup selects a bounded policy group from the HTTP operation.
|
||||
func requestGroup(ctx *fiber.Ctx) string {
|
||||
if ctx.Path() == "/api/v1/users" || strings.HasPrefix(ctx.Path(), "/api/v1/auth/") {
|
||||
return "auth"
|
||||
}
|
||||
if ctx.Method() == http.MethodGet {
|
||||
return "read"
|
||||
}
|
||||
return "write"
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
type sessionFixture struct {
|
||||
fixtureAuthentication
|
||||
login func(string, string) (dto.SessionDTO, error)
|
||||
logoutError error
|
||||
}
|
||||
|
||||
// Login delegates the credentials decoded by the controller to the arranged scenario.
|
||||
func (f sessionFixture) Login(_ context.Context, username, password string) (dto.SessionDTO, error) {
|
||||
return f.login(username, password)
|
||||
}
|
||||
|
||||
// Logout returns the prescribed revocation outcome.
|
||||
func (f sessionFixture) Logout(context.Context, string) error {
|
||||
return f.logoutError
|
||||
}
|
||||
|
||||
// TestLoginHTTPChecksBasicEncoding verifies independent wire-level login scenarios.
|
||||
func TestLoginHTTPChecksBasicEncoding(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
header string
|
||||
body string
|
||||
status int
|
||||
}{
|
||||
{"missing header", "", "", http.StatusUnauthorized},
|
||||
{"wrong scheme", "Bearer abc", "", http.StatusUnauthorized},
|
||||
{"bad base64", "Basic %%%", "", http.StatusUnauthorized},
|
||||
{"no delimiter", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice")), "", http.StatusUnauthorized},
|
||||
{"unexpected body", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "{}", http.StatusBadRequest},
|
||||
{"valid colon in password", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "", http.StatusCreated},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.auth = sessionFixture{login: func(username, password string) (dto.SessionDTO, error) {
|
||||
if username != "alice" || password != "long-password:ok" {
|
||||
t.Fatal("credentials altered")
|
||||
}
|
||||
return dto.SessionDTO{Token: "opaque", ExpiresAt: time.Now().UTC().Add(time.Hour), User: dto.UserDTO{ID: uuid.New(), Username: "alice"}}, nil
|
||||
}}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader(tc.body))
|
||||
req.Header.Set("Authorization", tc.header)
|
||||
response, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = response.Body.Close()
|
||||
}()
|
||||
if response.StatusCode != tc.status {
|
||||
t.Fatalf("got %d want %d", response.StatusCode, tc.status)
|
||||
}
|
||||
if tc.status == http.StatusUnauthorized && response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatal("missing Basic challenge")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginInvalidCredentialsUsesBasicChallenge checks the service rejection mapping.
|
||||
func TestLoginInvalidCredentialsUsesBasicChallenge(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.auth = sessionFixture{login: func(string, string) (dto.SessionDTO, error) {
|
||||
return dto.SessionDTO{}, service.ErrUnauthorized
|
||||
}}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
req.SetBasicAuth("alice", "invalid-password")
|
||||
response, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = response.Body.Close()
|
||||
}()
|
||||
if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatal("incorrect login rejection")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLogoutHTTPReturnsNoContent checks the authenticated revocation response.
|
||||
func TestLogoutHTTPReturnsNoContent(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+actor)
|
||||
response, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = response.Body.Close()
|
||||
}()
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if err != nil || response.StatusCode != http.StatusNoContent || len(body) != 0 {
|
||||
t.Fatalf("invalid logout response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLogoutHTTPPreservesFailure ensures an unsuccessful revoke does not claim success.
|
||||
func TestLogoutHTTPPreservesFailure(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
ctrl.auth = sessionFixture{fixtureAuthentication: fixtureAuthentication{ctrl.service}, logoutError: context.DeadlineExceeded}
|
||||
status, _, err := request(ctrl, http.MethodDelete, "/api/v1/auth/sessions/current", actor, nil)
|
||||
if err != nil || status != http.StatusInternalServerError {
|
||||
t.Fatalf("revocation failure hidden: %d %v", status, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyIdentityDoesNotAuthenticate verifies the lab1 header cannot grant access.
|
||||
func TestLegacyIdentityDoesNotAuthenticate(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
req.Header.Set("X-User-Id", actor)
|
||||
response, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = response.Body.Close()
|
||||
}()
|
||||
if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
||||
t.Fatal("legacy identity granted access or missing challenge")
|
||||
}
|
||||
}
|
||||
|
||||
type unavailableReadiness struct{}
|
||||
|
||||
// Ping simulates an unavailable mandatory dependency for readiness mapping.
|
||||
func (unavailableReadiness) Ping(context.Context) error {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
|
||||
// TestReadinessRejectsDependencyFailure verifies readiness reflects mandatory infrastructure.
|
||||
func TestReadinessRejectsDependencyFailure(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.readiness = unavailableReadiness{}
|
||||
status, _, err := request(ctrl, http.MethodGet, "/health/ready", "", nil)
|
||||
if err != nil || status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("incorrect readiness: %d %v", status, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// TestController_ChatsCreate checks membership and request validation in isolated chats.
|
||||
func TestController_ChatsCreate(t *testing.T) {
|
||||
t.Run("Positive: caller included", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusCreated, body)
|
||||
if body["title"] != "Team" || !reflect.DeepEqual(body["member_ids"], []any{actor}) {
|
||||
t.Fatalf("chat fields changed: %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: empty members", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: duplicate members", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, actor}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: caller omitted", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
outsider := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{outsider}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown member", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, uuid.NewString()}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed member ID", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, "invalid"}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: blank title", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": " ", "member_ids": []string{actor}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed JSON", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := []byte(`{`)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_ChatsGetByID checks access and the returned chat identity.
|
||||
func TestController_ChatsGetByID(t *testing.T) {
|
||||
t.Run("Positive: member reads chat", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor, target := owner, id
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusOK, body)
|
||||
if body["id"] != id || body["title"] != "Чат" {
|
||||
t.Fatalf("wrong chat: %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor, target := user(t, ctrl), id
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusNotFound, body)
|
||||
assertErrorCode(t, body, "not_found")
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown chat", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
actor, target := owner, uuid.NewString()
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusNotFound, body)
|
||||
assertErrorCode(t, body, "not_found")
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed chat ID", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
actor, target := owner, "invalid"
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: authentication precedes ID parsing", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor, target := "", "invalid"
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_ChatsGetPage checks that foreign memberships remain absent from lists.
|
||||
func TestController_ChatsGetPage(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
chat(t, ctrl, owner)
|
||||
outsider := user(t, ctrl)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats", outsider, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusOK, body)
|
||||
if len(body["items"].([]any)) != 0 || body["next_cursor"] != nil {
|
||||
t.Fatalf("foreign chat leaked: %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_ChatPagination recovers every chat exactly once across page boundaries.
|
||||
func TestController_ChatPagination(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
expected := make(map[string]bool)
|
||||
for range 15 {
|
||||
expected[chat(t, ctrl, actor)] = true
|
||||
}
|
||||
|
||||
// Act.
|
||||
items := history(t, ctrl, actor, "/api/v1/chats")
|
||||
|
||||
// Assert.
|
||||
if len(items) != len(expected) {
|
||||
t.Fatalf("got %d chats, want %d", len(items), len(expected))
|
||||
}
|
||||
for _, item := range items {
|
||||
id := item.(map[string]any)["id"].(string)
|
||||
if !expected[id] {
|
||||
t.Fatalf("duplicate or unexpected chat %s", id)
|
||||
}
|
||||
delete(expected, id)
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_ChatCursorScope rejects a continuation issued for another user's list.
|
||||
func TestController_ChatCursorScope(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
outsider := user(t, ctrl)
|
||||
chat(t, ctrl, owner)
|
||||
chat(t, ctrl, owner)
|
||||
page := call(t, ctrl, http.MethodGet, "/api/v1/chats?limit=1", owner, nil, http.StatusOK)
|
||||
token := page["next_cursor"].(string)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats?cursor="+url.QueryEscape(token), outsider, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/recover"
|
||||
)
|
||||
|
||||
// configure initializes the HTTP server, middleware and routes.
|
||||
func (ctrl *Controller) configure() {
|
||||
ctrl.createServer()
|
||||
ctrl.initMiddlewares()
|
||||
ctrl.initRoutes()
|
||||
}
|
||||
|
||||
// createServer creates Fiber with the configured transport limits and error handler.
|
||||
func (ctrl *Controller) createServer() {
|
||||
timeout := ctrl.cfg.Timeout()
|
||||
ctrl.server = fiber.New(fiber.Config{
|
||||
AppName: "messenger-lab1",
|
||||
DisableStartupMessage: true,
|
||||
Immutable: true,
|
||||
CaseSensitive: true,
|
||||
StrictRouting: true,
|
||||
BodyLimit: ctrl.cfg.MaxBodyBytes,
|
||||
Concurrency: ctrl.cfg.MaxConnections,
|
||||
ReadTimeout: timeout,
|
||||
WriteTimeout: timeout,
|
||||
IdleTimeout: timeout,
|
||||
ErrorHandler: ctrl.handleErr,
|
||||
})
|
||||
}
|
||||
|
||||
// initMiddlewares registers request logging and panic recovery middleware.
|
||||
func (ctrl *Controller) initMiddlewares() {
|
||||
ctrl.server.Use(ctrl.request)
|
||||
ctrl.server.Use(recover.New())
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Package fiber implements the messenger HTTP transport using Fiber.
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.lab260.ru/fielderr"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/controller"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// Controller owns the HTTP server and delegates business operations to Service.
|
||||
// Its configuration is copied at construction and must not change during serving.
|
||||
// Fx manages its listener through Start and Stop.
|
||||
type Controller struct {
|
||||
log *zap.Logger
|
||||
cfg config.Controller
|
||||
service service.Service
|
||||
server *fiber.App
|
||||
errorRegistry *fielderr.Registry
|
||||
admission admission.Distributed
|
||||
auth service.Authentication
|
||||
readiness Readiness
|
||||
stopping atomic.Bool
|
||||
serveDone chan error
|
||||
}
|
||||
|
||||
var _ controller.Controller = (*Controller)(nil)
|
||||
|
||||
// New validates dependencies and prepares the server without opening a listener.
|
||||
// Routing, middleware and Fiber configuration are installed by configure.
|
||||
func New(log *zap.Logger, cfg *config.Controller, svc service.Service, registry *fielderr.Registry, limiter admission.Distributed, auth service.Authentication, readiness Readiness) (*Controller, error) {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if log == nil || svc == nil || registry == nil || limiter == nil || auth == nil || readiness == nil {
|
||||
return nil, fmt.Errorf("HTTP logger, service, error registry and admission limiter are required")
|
||||
}
|
||||
ctrl := &Controller{
|
||||
log: log.Named("controller.http.fiber"),
|
||||
cfg: *cfg,
|
||||
service: svc,
|
||||
errorRegistry: registry,
|
||||
admission: limiter,
|
||||
auth: auth,
|
||||
readiness: readiness,
|
||||
serveDone: make(chan error, 1),
|
||||
}
|
||||
ctrl.configure()
|
||||
return ctrl, nil
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service/production"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store/memory"
|
||||
)
|
||||
|
||||
// testController creates an integration fixture with the real controller, service and store.
|
||||
func testController(t *testing.T, change func(*config.Config)) *Controller {
|
||||
t.Helper()
|
||||
cfg := config.Default()
|
||||
cfg.HTTP.Admission.RequestsPerSecond = 100000
|
||||
cfg.HTTP.Admission.Burst = 100000
|
||||
if change != nil {
|
||||
change(cfg)
|
||||
}
|
||||
repo, err := memory.New(cfg.Memory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc, err := production.New(repo, codec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry, err := NewErrorRegistry()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
limiter, err := admission.New(admission.Options{
|
||||
MaxInFlight: cfg.HTTP.Admission.MaxInFlight,
|
||||
RequestsPerSecond: cfg.HTTP.Admission.RequestsPerSecond,
|
||||
Burst: cfg.HTTP.Admission.Burst,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctrl, err := New(zap.NewNop(), cfg.HTTP, svc, registry, &fixtureAdmission{limiter}, fixtureAuthentication{svc}, fixtureReadiness{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ctrl
|
||||
}
|
||||
|
||||
// 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))
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if actor != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+actor)
|
||||
}
|
||||
resp, err := ctrl.server.Test(req, 10000)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
var data map[string]any
|
||||
if err = json.Unmarshal(b, &data); err != nil {
|
||||
return resp.StatusCode, nil, fmt.Errorf("invalid JSON response: %w", err)
|
||||
}
|
||||
if resp.Header.Get("X-Request-Id") == "" {
|
||||
return resp.StatusCode, data, fmt.Errorf("missing request ID")
|
||||
}
|
||||
if resp.StatusCode >= http.StatusBadRequest {
|
||||
envelope, ok := data["error"].(map[string]any)
|
||||
if !ok || envelope["request_id"] != resp.Header.Get("X-Request-Id") {
|
||||
return resp.StatusCode, data, fmt.Errorf("invalid error envelope")
|
||||
}
|
||||
}
|
||||
return resp.StatusCode, data, nil
|
||||
}
|
||||
|
||||
// call sends a JSON test request and checks its expected HTTP status.
|
||||
func call(t *testing.T, ctrl *Controller, method, path, actor string, body any, want int) map[string]any {
|
||||
t.Helper()
|
||||
var b []byte
|
||||
var err error
|
||||
if raw, ok := body.([]byte); ok {
|
||||
b = raw
|
||||
} else if body != nil {
|
||||
b, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
status, data, err := request(ctrl, method, path, actor, b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != want {
|
||||
t.Fatalf("%s %s: got %d want %d: %v", method, path, status, want, data)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// user creates a test user and returns its identifier.
|
||||
func user(t *testing.T, c *Controller) string {
|
||||
t.Helper()
|
||||
r := call(t, c, http.MethodPost, "/api/v1/users", "", map[string]any{"username": "u_" + uuid.New().String()[:8], "display_name": "Алиса 👋", "password": "fixture-password-123"}, http.StatusCreated)
|
||||
return r["id"].(string)
|
||||
}
|
||||
|
||||
// chat creates a test chat containing the supplied user.
|
||||
func chat(t *testing.T, c *Controller, u string) string {
|
||||
t.Helper()
|
||||
r := call(t, c, http.MethodPost, "/api/v1/chats", u, map[string]any{"title": "Чат", "member_ids": []string{u}}, http.StatusCreated)
|
||||
return r["id"].(string)
|
||||
}
|
||||
|
||||
// TestDuplicateUsernameRace checks username uniqueness under concurrent requests.
|
||||
func TestDuplicateUsernameRace(t *testing.T) {
|
||||
// Arrange.
|
||||
c := testController(t, nil)
|
||||
results := make(chan int, 10)
|
||||
failures := make(chan error, 10)
|
||||
var wg sync.WaitGroup
|
||||
// Act.
|
||||
for range 10 {
|
||||
wg.Go(func() {
|
||||
status, _, err := request(c, http.MethodPost, "/api/v1/users", "", []byte(`{"username":"same","display_name":"User","password":"fixture-password-123"}`))
|
||||
if err != nil {
|
||||
failures <- err
|
||||
}
|
||||
results <- status
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
close(failures)
|
||||
// Assert.
|
||||
for err := range failures {
|
||||
t.Error(err)
|
||||
}
|
||||
created, conflicts := 0, 0
|
||||
for s := range results {
|
||||
switch s {
|
||||
case http.StatusCreated:
|
||||
created++
|
||||
case http.StatusConflict:
|
||||
conflicts++
|
||||
default:
|
||||
t.Errorf("unexpected %d", s)
|
||||
}
|
||||
}
|
||||
if created != 1 || conflicts != 9 {
|
||||
t.Fatalf("created=%d conflicts=%d", created, conflicts)
|
||||
}
|
||||
}
|
||||
|
||||
// history collects all test messages by following pagination cursors.
|
||||
func history(t *testing.T, c *Controller, u, path string) []any {
|
||||
t.Helper()
|
||||
var items []any
|
||||
next := path + "?limit=7"
|
||||
for range 100 {
|
||||
r := call(t, c, http.MethodGet, next, u, nil, http.StatusOK)
|
||||
items = append(items, r["items"].([]any)...)
|
||||
if r["next_cursor"] == nil {
|
||||
return items
|
||||
}
|
||||
next = path + "?limit=7&cursor=" + url.QueryEscape(r["next_cursor"].(string))
|
||||
}
|
||||
t.Fatal("pagination never finished")
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestConcurrent100Messages10Clients recovers the exact acknowledged records after concurrent writes.
|
||||
func TestConcurrent100Messages10Clients(t *testing.T) {
|
||||
// Arrange.
|
||||
const clients = 10
|
||||
const messagesPerClient = 10
|
||||
const total = clients * messagesPerClient
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
chatID := chat(t, ctrl, actor)
|
||||
path := "/api/v1/chats/" + chatID + "/messages"
|
||||
acknowledgements := make(chan map[string]any, total)
|
||||
failures := make(chan error, total)
|
||||
var writers sync.WaitGroup
|
||||
|
||||
// Act.
|
||||
for client := range clients {
|
||||
writers.Go(func() {
|
||||
for index := range messagesPerClient {
|
||||
text := fmt.Sprintf("client %d message %d", client, index)
|
||||
payload, err := json.Marshal(map[string]string{"text": text})
|
||||
if err != nil {
|
||||
failures <- err
|
||||
continue
|
||||
}
|
||||
status, body, err := request(ctrl, http.MethodPost, path, actor, payload)
|
||||
if err != nil {
|
||||
failures <- err
|
||||
continue
|
||||
}
|
||||
if status != http.StatusCreated || body["text"] != text || body["sender_id"] != actor || body["chat_id"] != chatID {
|
||||
failures <- fmt.Errorf("incorrect acknowledgement: status=%d, body=%v", status, body)
|
||||
continue
|
||||
}
|
||||
acknowledgements <- body
|
||||
}
|
||||
})
|
||||
}
|
||||
writers.Wait()
|
||||
close(failures)
|
||||
close(acknowledgements)
|
||||
|
||||
// Assert.
|
||||
for err := range failures {
|
||||
t.Error(err)
|
||||
}
|
||||
if t.Failed() {
|
||||
t.FailNow()
|
||||
}
|
||||
expected := make(map[string]map[string]any, total)
|
||||
for message := range acknowledgements {
|
||||
id, ok := message["id"].(string)
|
||||
if !ok || id == "" {
|
||||
t.Fatalf("invalid message ID: %v", message)
|
||||
}
|
||||
if _, duplicate := expected[id]; duplicate {
|
||||
t.Fatalf("duplicate acknowledgement ID %s", id)
|
||||
}
|
||||
expected[id] = message
|
||||
}
|
||||
if len(expected) != total {
|
||||
t.Fatalf("acknowledged=%d, want=%d", len(expected), total)
|
||||
}
|
||||
items := history(t, ctrl, actor, path)
|
||||
if len(items) != total {
|
||||
t.Fatalf("recovered=%d, want=%d", len(items), total)
|
||||
}
|
||||
for _, item := range items {
|
||||
message := item.(map[string]any)
|
||||
id := message["id"].(string)
|
||||
if !reflect.DeepEqual(message, expected[id]) {
|
||||
t.Fatalf("stored record differs from acknowledgement: got=%v, want=%v", message, expected[id])
|
||||
}
|
||||
delete(expected, id)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnsupportedMediaType checks rejection of unsupported request content types.
|
||||
func TestUnsupportedMediaType(t *testing.T) {
|
||||
// Arrange.
|
||||
c := testController(t, nil)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{}`))
|
||||
req.Header.Set("Content-Type", "text/plain")
|
||||
// Act.
|
||||
r, e := c.server.Test(req)
|
||||
|
||||
// Assert.
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if r.StatusCode != http.StatusUnsupportedMediaType {
|
||||
t.Fatalf("status %d", r.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfigIndependentState prevents one application instance from accepting another's identity.
|
||||
func TestConfigIndependentState(t *testing.T) {
|
||||
// Arrange.
|
||||
first := testController(t, nil)
|
||||
actor := user(t, first)
|
||||
second := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(second, http.MethodGet, "/api/v1/users/me", actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
}
|
||||
|
||||
// mustJSON encodes fixture payloads and reports preparation failures at the caller.
|
||||
func mustJSON(t *testing.T, value any) []byte {
|
||||
t.Helper()
|
||||
payload, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"mime"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/strictjson"
|
||||
)
|
||||
|
||||
// decode checks HTTP media type and maps strict JSON decoding errors to API input errors.
|
||||
func decode(ctx *fiber.Ctx, target any, requiredFields ...string) error {
|
||||
mediaType, _, err := mime.ParseMediaType(ctx.Get(fiber.HeaderContentType))
|
||||
if err != nil || mediaType != fiber.MIMEApplicationJSON {
|
||||
return errMedia
|
||||
}
|
||||
if err := strictjson.DecodeObject(ctx.Body(), target, requiredFields...); err != nil {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package fiber
|
||||
|
||||
import "context"
|
||||
|
||||
// Readiness checks the dependencies required by the synchronous request path.
|
||||
type Readiness interface {
|
||||
// Ping reports whether requests can be safely served.
|
||||
Ping(context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package fiber
|
||||
|
||||
const (
|
||||
// codeInvalid identifies malformed or invalid request input.
|
||||
codeInvalid = "invalid_request"
|
||||
// codeUnauthorized identifies an unresolved user identity.
|
||||
codeUnauthorized = "unauthorized"
|
||||
// codeNotFound deliberately covers both absent and inaccessible resources.
|
||||
codeNotFound = "not_found"
|
||||
// codeConflict identifies a violated uniqueness constraint.
|
||||
codeConflict = "conflict"
|
||||
// codeUnavailable identifies temporary admission or persistent capacity exhaustion.
|
||||
codeUnavailable = "unavailable"
|
||||
// codeRateLimited identifies exhaustion of the request token bucket.
|
||||
codeRateLimited = "rate_limited"
|
||||
// codeTooLarge identifies a request exceeding the transport byte budget.
|
||||
codeTooLarge = "payload_too_large"
|
||||
// codeMedia identifies an unsupported request media type.
|
||||
codeMedia = "unsupported_media_type"
|
||||
// codeInternal identifies a hidden unexpected failure.
|
||||
codeInternal = "internal_error"
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.lab260.ru/fielderr"
|
||||
)
|
||||
|
||||
// NewErrorRegistry returns an immutable mapping of application statuses to HTTP codes.
|
||||
// The registry is injected rather than installed in process-global state, allowing
|
||||
// independent application instances in integration tests.
|
||||
func NewErrorRegistry() (*fielderr.Registry, error) {
|
||||
return fielderr.NewRegistry(
|
||||
statusDefinition(codeInvalid, http.StatusBadRequest),
|
||||
statusDefinition(codeUnauthorized, http.StatusUnauthorized),
|
||||
statusDefinition(codeNotFound, http.StatusNotFound),
|
||||
statusDefinition(codeConflict, http.StatusConflict),
|
||||
statusDefinition(codeTooLarge, http.StatusRequestEntityTooLarge),
|
||||
statusDefinition(codeMedia, http.StatusUnsupportedMediaType),
|
||||
statusDefinition(codeRateLimited, http.StatusTooManyRequests),
|
||||
statusDefinition(codeUnavailable, http.StatusServiceUnavailable),
|
||||
statusDefinition(codeInternal, http.StatusInternalServerError),
|
||||
)
|
||||
}
|
||||
|
||||
// statusDefinition associates an application error code with its HTTP status.
|
||||
func statusDefinition(name string, httpStatus int) fielderr.StatusDefinition {
|
||||
return fielderr.StatusDefinition{
|
||||
Code: fielderr.NewStatusCode(name),
|
||||
Name: name,
|
||||
HTTPStatus: httpStatus,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
"go.lab260.ru/fielderr"
|
||||
"go.uber.org/zap"
|
||||
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/http"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// handleErr normalizes a failure and writes the public error envelope.
|
||||
func (ctrl *Controller) handleErr(ctx *fiber.Ctx, err error) error {
|
||||
requestID := ctx.GetRespHeader(headerRequestID)
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewString()
|
||||
ctx.Set(headerRequestID, requestID)
|
||||
}
|
||||
err = publicError(normalizeTransportError(err))
|
||||
status, ok := fielderr.HTTPStatusFrom(ctrl.errorRegistry, err)
|
||||
if !ok {
|
||||
err = errInternal
|
||||
status = http.StatusInternalServerError
|
||||
}
|
||||
if status == http.StatusUnauthorized {
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if ctx.Path() == "/api/v1/auth/sessions" && ctx.Method() == http.MethodPost {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
ctx.Set(fiber.HeaderWWWAuthenticate, challenge)
|
||||
}
|
||||
if status == http.StatusInternalServerError {
|
||||
ctrl.log.Error("unexpected request failure", zap.String("request_id", requestID))
|
||||
}
|
||||
return ctx.Status(status).JSON(errorResponse(err, requestID))
|
||||
}
|
||||
|
||||
// normalizeTransportError maps Fiber failures to transport-independent application errors.
|
||||
func normalizeTransportError(err error) error {
|
||||
transportError, ok := errors.AsType[*fiber.Error](err)
|
||||
if !ok {
|
||||
return err
|
||||
}
|
||||
switch transportError.Code {
|
||||
case http.StatusRequestEntityTooLarge:
|
||||
return errTooLarge
|
||||
case http.StatusNotFound, http.StatusMethodNotAllowed:
|
||||
return service.ErrNotFound
|
||||
case http.StatusBadRequest, http.StatusRequestTimeout, http.StatusRequestHeaderFieldsTooLarge:
|
||||
return service.ErrInvalid
|
||||
default:
|
||||
return errInternal
|
||||
}
|
||||
}
|
||||
|
||||
// errorResponse builds the public error envelope with its request identifier.
|
||||
func errorResponse(err error, requestID string) httpmodel.ErrorResponse {
|
||||
status, _ := fielderr.Status(err)
|
||||
message, _ := fielderr.PublicMessage(err)
|
||||
return httpmodel.ErrorResponse{
|
||||
Error: httpmodel.ErrorDetail{
|
||||
Code: status.String(),
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/valyala/fasthttp"
|
||||
"go.lab260.ru/fielderr"
|
||||
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/http"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// TestTransportErrorMapping checks safe API errors for framework-generated failures.
|
||||
func TestTransportErrorMapping(t *testing.T) {
|
||||
t.Run("large body", func(t *testing.T) {
|
||||
if normalizeTransportError(fiber.ErrRequestEntityTooLarge) != errTooLarge {
|
||||
t.Fatal("incorrect body-limit error")
|
||||
}
|
||||
})
|
||||
t.Run("method not allowed", func(t *testing.T) {
|
||||
if normalizeTransportError(fiber.ErrMethodNotAllowed) != service.ErrNotFound {
|
||||
t.Fatal("unexpected method error")
|
||||
}
|
||||
})
|
||||
t.Run("invalid request", func(t *testing.T) {
|
||||
if normalizeTransportError(fiber.ErrBadRequest) != service.ErrInvalid {
|
||||
t.Fatal("unexpected input error")
|
||||
}
|
||||
})
|
||||
t.Run("unexpected framework failure", func(t *testing.T) {
|
||||
if normalizeTransportError(fiber.ErrInternalServerError) != errInternal {
|
||||
t.Fatal("unexpected failure escaped normalization")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_handleErr writes a safe, correlated fallback response.
|
||||
func TestController_handleErr(t *testing.T) {
|
||||
t.Run("Negative: unknown internal error", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
raw := &fasthttp.RequestCtx{}
|
||||
ctx := ctrl.server.AcquireCtx(raw)
|
||||
defer ctrl.server.ReleaseCtx(ctx)
|
||||
|
||||
// Act.
|
||||
err := ctrl.handleErr(ctx, errors.New("private storage secret"))
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw.Response.StatusCode() != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d", raw.Response.StatusCode())
|
||||
}
|
||||
var body httpmodel.ErrorResponse
|
||||
if err := json.Unmarshal(raw.Response.Body(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requestID := string(raw.Response.Header.Peek(headerRequestID))
|
||||
if requestID == "" || body.Error.RequestID != requestID {
|
||||
t.Fatalf("uncorrelated error: %+v, header=%q", body, requestID)
|
||||
}
|
||||
if body.Error.Code != "internal_error" || body.Error.Message != "internal server error" {
|
||||
t.Fatalf("unsafe fallback: %+v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing status mapping", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
registry, err := fielderr.NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctrl.errorRegistry = registry
|
||||
raw := &fasthttp.RequestCtx{}
|
||||
ctx := ctrl.server.AcquireCtx(raw)
|
||||
defer ctrl.server.ReleaseCtx(ctx)
|
||||
|
||||
// Act.
|
||||
err = ctrl.handleErr(ctx, service.ErrInvalid)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw.Response.StatusCode() != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d", raw.Response.StatusCode())
|
||||
}
|
||||
var body httpmodel.ErrorResponse
|
||||
if err := json.Unmarshal(raw.Response.Body(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requestID := string(raw.Response.Header.Peek(headerRequestID))
|
||||
if requestID == "" || body.Error.RequestID != requestID {
|
||||
t.Fatalf("uncorrelated error: %+v, header=%q", body, requestID)
|
||||
}
|
||||
if body.Error.Code != "internal_error" || body.Error.Message != "internal server error" {
|
||||
t.Fatalf("unsafe fallback: %+v", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// fixtureAuthentication isolates HTTP decoding and business authorization from session persistence.
|
||||
type fixtureAuthentication struct {
|
||||
service service.Service
|
||||
}
|
||||
|
||||
// Register delegates profile validation to the real business service.
|
||||
func (f fixtureAuthentication) Register(ctx context.Context, request dto.UsersCreateRequestDTO, _ string) (dto.UserDTO, error) {
|
||||
return f.service.UsersCreate(ctx, request)
|
||||
}
|
||||
|
||||
// Authenticate uses fixture tokens equal to user IDs exclusively in controller tests.
|
||||
func (f fixtureAuthentication) Authenticate(ctx context.Context, token string) (string, error) {
|
||||
return token, f.service.UsersCheckIdentity(ctx, token)
|
||||
}
|
||||
|
||||
// Login is deliberately unsupported by this fixture; real login has separate integration coverage.
|
||||
func (f fixtureAuthentication) Login(context.Context, string, string) (dto.SessionDTO, error) {
|
||||
return dto.SessionDTO{}, service.ErrUnauthorized
|
||||
}
|
||||
|
||||
// Logout accepts the fixture session without persistent side effects.
|
||||
func (f fixtureAuthentication) Logout(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type fixtureReadiness struct{}
|
||||
|
||||
// Ping marks isolated controller fixtures ready without external resources.
|
||||
func (fixtureReadiness) Ping(context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type fixtureAdmission struct {
|
||||
*admission.Limiter
|
||||
}
|
||||
|
||||
// Enter adapts the deterministic local policy fixture to the distributed boundary.
|
||||
func (f *fixtureAdmission) Enter(_ context.Context, _, user string) (func(), error) {
|
||||
if user != "" {
|
||||
return func() {
|
||||
}, nil
|
||||
}
|
||||
if !f.Allow(time.Now()) {
|
||||
return nil, admission.ErrRate
|
||||
}
|
||||
if !f.Acquire() {
|
||||
return nil, admission.ErrSlots
|
||||
}
|
||||
return f.Release, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/http"
|
||||
)
|
||||
|
||||
// HandleUsersCreate decodes registration input and returns the created user.
|
||||
func (ctrl *Controller) HandleUsersCreate(ctx *fiber.Ctx) error {
|
||||
var request httpmodel.UsersCreateRequest
|
||||
if err := decode(ctx, &request, "username", "display_name", "password"); err != nil {
|
||||
return err
|
||||
}
|
||||
user, err := ctrl.auth.Register(ctx.UserContext(), dto.UsersCreateRequestDTO{
|
||||
Username: request.Username,
|
||||
DisplayName: request.DisplayName,
|
||||
}, request.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusCreated).JSON(userResponse(user))
|
||||
}
|
||||
|
||||
// HandleUsersGetMe returns the account selected by the validated session.
|
||||
func (ctrl *Controller) HandleUsersGetMe(ctx *fiber.Ctx) error {
|
||||
user, err := ctrl.service.UsersGetMe(ctx.UserContext(), identity(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusOK).JSON(userResponse(user))
|
||||
}
|
||||
|
||||
// HandleChatsCreate decodes the chat payload and returns the new chat.
|
||||
func (ctrl *Controller) HandleChatsCreate(ctx *fiber.Ctx) error {
|
||||
var request httpmodel.ChatsCreateRequest
|
||||
if err := decode(ctx, &request, "title", "member_ids"); err != nil {
|
||||
return err
|
||||
}
|
||||
chat, err := ctrl.service.ChatsCreate(ctx.UserContext(), dto.ChatsCreateRequestDTO{
|
||||
UserID: identity(ctx),
|
||||
Title: request.Title,
|
||||
MemberIDs: request.MemberIDs,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusCreated).JSON(chatResponse(chat))
|
||||
}
|
||||
|
||||
// HandleChatsGetByID delegates chat authorization and maps the accessible chat.
|
||||
func (ctrl *Controller) HandleChatsGetByID(ctx *fiber.Ctx) error {
|
||||
chat, err := ctrl.service.ChatsGetByID(ctx.UserContext(), identity(ctx), ctx.Params("chat_id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusOK).JSON(chatResponse(chat))
|
||||
}
|
||||
|
||||
// HandleChatsGetPage returns the service's page of visible chats.
|
||||
func (ctrl *Controller) HandleChatsGetPage(ctx *fiber.Ctx) error {
|
||||
page, err := ctrl.service.ChatsGetPage(ctx.UserContext(), pageRequest(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusOK).JSON(chatPageResponse(page))
|
||||
}
|
||||
|
||||
// HandleMessagesCreate decodes text; the service derives and authorizes the sender.
|
||||
func (ctrl *Controller) HandleMessagesCreate(ctx *fiber.Ctx) error {
|
||||
var request httpmodel.MessagesCreateRequest
|
||||
if err := decode(ctx, &request, "text"); err != nil {
|
||||
return err
|
||||
}
|
||||
message, err := ctrl.service.MessagesCreate(ctx.UserContext(), dto.MessagesCreateRequestDTO{
|
||||
UserID: identity(ctx),
|
||||
ChatID: ctx.Params("chat_id"),
|
||||
Text: request.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusCreated).JSON(messageResponse(message))
|
||||
}
|
||||
|
||||
// HandleMessagesGetPage returns the service's ordered history page.
|
||||
func (ctrl *Controller) HandleMessagesGetPage(ctx *fiber.Ctx) error {
|
||||
page, err := ctrl.service.MessagesGetPage(ctx.UserContext(), pageRequest(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusOK).JSON(messagePageResponse(page))
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package fiber
|
||||
|
||||
const (
|
||||
headerUserID = "X-User-Id"
|
||||
headerRequestID = "X-Request-Id"
|
||||
retryAfterSeconds = 1
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// handleLive reports that the server process is running.
|
||||
func (ctrl *Controller) handleLive(ctx *fiber.Ctx) error {
|
||||
return ctx.JSON(fiber.Map{"status": "ok"})
|
||||
}
|
||||
|
||||
// handleReady reports readiness unless shutdown has started.
|
||||
func (ctrl *Controller) handleReady(ctx *fiber.Ctx) error {
|
||||
if ctrl.stopping.Load() {
|
||||
return errBusy
|
||||
}
|
||||
if err := ctrl.readiness.Ping(ctx.UserContext()); err != nil {
|
||||
return errBusy
|
||||
}
|
||||
return ctrl.handleLive(ctx)
|
||||
}
|
||||
|
||||
// handleNotFound returns the application error for an unmatched route.
|
||||
func (ctrl *Controller) handleNotFound(_ *fiber.Ctx) error {
|
||||
return service.ErrNotFound
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Start opens the listener synchronously so Fx observes bind errors immediately.
|
||||
// It must be called once per Controller; Stop terminates the serving goroutine.
|
||||
func (ctrl *Controller) Start(ctx context.Context) error {
|
||||
listener, err := net.Listen("tcp", ctrl.cfg.Bind())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ready := make(chan struct{})
|
||||
go ctrl.serve(&acceptingListener{Listener: listener, ready: ready})
|
||||
select {
|
||||
case <-ready:
|
||||
ctrl.log.Info("http listener started", zap.String("address", listener.Addr().String()))
|
||||
return nil
|
||||
case err := <-ctrl.serveDone:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
_ = listener.Close()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// acceptingListener signals after fasthttp registers the listener and enters its
|
||||
// accept loop. An OnListen hook runs earlier and cannot guarantee safe immediate Stop.
|
||||
type acceptingListener struct {
|
||||
// Listener is the bound socket owned by the HTTP lifecycle.
|
||||
net.Listener
|
||||
ready chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// Accept marks the server as started before waiting for the next connection.
|
||||
func (listener *acceptingListener) Accept() (net.Conn, error) {
|
||||
listener.once.Do(func() {
|
||||
close(listener.ready)
|
||||
})
|
||||
return listener.Listener.Accept()
|
||||
}
|
||||
|
||||
// serve serves the listener and publishes its terminal result to the lifecycle.
|
||||
func (ctrl *Controller) serve(listener net.Listener) {
|
||||
ctrl.serveDone <- ctrl.server.Listener(listener)
|
||||
}
|
||||
|
||||
// Stop disables admission, closes the listener and drains active requests.
|
||||
// The configured timeout is bounded by the caller's Fx shutdown context.
|
||||
func (ctrl *Controller) Stop(ctx context.Context) error {
|
||||
ctrl.stopping.Store(true)
|
||||
ctx, cancel := context.WithTimeout(ctx, ctrl.cfg.ShutdownTimeout())
|
||||
defer cancel()
|
||||
if err := ctrl.server.ShutdownWithContext(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case err := <-ctrl.serveDone:
|
||||
ctrl.log.Info("http listener stopped")
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// TestImmediateShutdown checks the startup/stop race without waiting for a first request.
|
||||
func TestImmediateShutdown(t *testing.T) {
|
||||
const repetitions = 10
|
||||
const stopDeadline = time.Second
|
||||
for range repetitions {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
// Select an ephemeral test port after validating the normal application config.
|
||||
ctrl.cfg.Host = "127.0.0.1"
|
||||
ctrl.cfg.Port = 0
|
||||
if err := ctrl.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), stopDeadline)
|
||||
// Act.
|
||||
err := ctrl.Stop(ctx)
|
||||
cancel()
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatalf("immediate shutdown leaked the listener or serve goroutine: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_Stop_ActiveRequestDeadline bounds draining while a real handler is still running.
|
||||
func TestController_Stop_ActiveRequestDeadline(t *testing.T) {
|
||||
// Arrange.
|
||||
const deadline = 3 * time.Second
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.cfg.Host = "127.0.0.1"
|
||||
ctrl.cfg.Port = 0
|
||||
// Install one controlled handler to test lifecycle independently of business routes.
|
||||
ctrl.createServer()
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
address := make(chan string, 1)
|
||||
ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error {
|
||||
address <- net.JoinHostPort(data.Host, data.Port)
|
||||
return nil
|
||||
})
|
||||
ctrl.server.Get("/blocked", func(ctx *fiber.Ctx) error {
|
||||
close(entered)
|
||||
<-release
|
||||
return ctx.SendStatus(http.StatusOK)
|
||||
})
|
||||
if err := ctrl.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &http.Client{Timeout: deadline}
|
||||
completed := make(chan error, 1)
|
||||
go func() {
|
||||
response, err := client.Get("http://" + <-address + "/blocked")
|
||||
if err == nil {
|
||||
err = response.Body.Close()
|
||||
}
|
||||
completed <- err
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
close(release)
|
||||
select {
|
||||
case err := <-completed:
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
case <-time.After(deadline):
|
||||
t.Error("blocked request did not terminate after release")
|
||||
}
|
||||
stopCtx, cancel := context.WithTimeout(context.Background(), deadline)
|
||||
defer cancel()
|
||||
if err := ctrl.Stop(stopCtx); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(deadline):
|
||||
t.Fatal("request did not reach handler")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
|
||||
// Act.
|
||||
err := ctrl.Stop(ctx)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("expected canceled drain, got %v", err)
|
||||
}
|
||||
if !ctrl.stopping.Load() {
|
||||
t.Fatal("shutdown did not disable admission")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanceledStartup closes its socket while server initialization is still blocked.
|
||||
func TestCanceledStartup(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.cfg.Host = "127.0.0.1"
|
||||
ctrl.cfg.Port = 0
|
||||
release := make(chan struct{})
|
||||
ctrl.server.Hooks().OnListen(func(_ fiber.ListenData) error {
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
// Act.
|
||||
err := ctrl.Start(ctx)
|
||||
close(release)
|
||||
// Assert.
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("expected canceled startup, got %v", err)
|
||||
}
|
||||
select {
|
||||
case <-ctrl.serveDone:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("serving goroutine leaked after canceled startup")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/http"
|
||||
)
|
||||
|
||||
// userResponse converts a user DTO into its HTTP representation.
|
||||
func userResponse(user dto.UserDTO) httpmodel.UserResponse {
|
||||
return httpmodel.UserResponse{
|
||||
ID: user.ID.String(),
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: user.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// chatResponse converts a chat DTO and its member identifiers into an HTTP response.
|
||||
func chatResponse(chat dto.ChatDTO) httpmodel.ChatResponse {
|
||||
members := make([]string, len(chat.MemberIDs))
|
||||
for index, id := range chat.MemberIDs {
|
||||
members[index] = id.String()
|
||||
}
|
||||
return httpmodel.ChatResponse{
|
||||
ID: chat.ID.String(),
|
||||
Title: chat.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: chat.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// messageResponse converts a message DTO into its HTTP representation.
|
||||
func messageResponse(message dto.MessageDTO) httpmodel.MessageResponse {
|
||||
return httpmodel.MessageResponse{
|
||||
ID: message.ID.String(),
|
||||
ChatID: message.ChatID.String(),
|
||||
SenderID: message.SenderID.String(),
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// pageRequest extracts identity, resource and pagination parameters from the request.
|
||||
func pageRequest(ctx *fiber.Ctx) dto.PageRequestDTO {
|
||||
return dto.PageRequestDTO{
|
||||
UserID: identity(ctx),
|
||||
ChatID: ctx.Params("chat_id"),
|
||||
Limit: ctx.Query("limit"),
|
||||
Cursor: ctx.Query("cursor"),
|
||||
}
|
||||
}
|
||||
|
||||
// chatPageResponse converts a page of chat DTOs into an HTTP response.
|
||||
func chatPageResponse(page dto.ChatPageDTO) httpmodel.ChatPageResponse {
|
||||
response := httpmodel.ChatPageResponse{
|
||||
Items: make([]httpmodel.ChatResponse, len(page.Items)),
|
||||
NextCursor: page.NextCursor,
|
||||
}
|
||||
for index, chat := range page.Items {
|
||||
response.Items[index] = chatResponse(chat)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
// messagePageResponse converts a page of message DTOs into an HTTP response.
|
||||
func messagePageResponse(page dto.MessagePageDTO) httpmodel.MessagePageResponse {
|
||||
response := httpmodel.MessagePageResponse{
|
||||
Items: make([]httpmodel.MessageResponse, len(page.Items)),
|
||||
NextCursor: page.NextCursor,
|
||||
}
|
||||
for index, message := range page.Items {
|
||||
response.Items[index] = messageResponse(message)
|
||||
}
|
||||
return response
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
)
|
||||
|
||||
// TestController_MessagesCreate checks message validation and identity-derived sender fields.
|
||||
func TestController_MessagesCreate(t *testing.T) {
|
||||
t.Run("Positive: Unicode at rune limit", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
text := strings.Repeat("界", 4000)
|
||||
payload := mustJSON(t, map[string]string{"text": text})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusCreated, body)
|
||||
if body["sender_id"] != owner || body["chat_id"] != id || body["text"] != text {
|
||||
t.Fatalf("message fields changed: %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: empty text", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
payload := mustJSON(t, map[string]string{"text": ""})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: whitespace text", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
payload := mustJSON(t, map[string]string{"text": " \n\t"})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: text exceeds rune limit", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
payload := mustJSON(t, map[string]string{"text": strings.Repeat("界", 4001)})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: sender spoof", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
outsider := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]string{"text": "hello", "sender_id": outsider})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]string{"text": "hello"})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusNotFound, body)
|
||||
assertErrorCode(t, body, "not_found")
|
||||
})
|
||||
|
||||
t.Run("Negative: authentication precedes JSON decoding", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := ""
|
||||
payload := []byte(`{`)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_MessagesGetPage rejects invalid pagination separately from access failures.
|
||||
func TestController_MessagesGetPage(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
query string
|
||||
outsider bool
|
||||
status int
|
||||
code string
|
||||
}{
|
||||
{"Negative: zero limit", "limit=0", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: limit above maximum", "limit=101", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: negative limit", "limit=-1", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: nonnumeric limit", "limit=x", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: fractional limit", "limit=1.0", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: malformed cursor", "cursor=invalid", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: outsider", "", true, http.StatusNotFound, "not_found"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
id := chat(t, ctrl, actor)
|
||||
if tc.outsider {
|
||||
actor = user(t, ctrl)
|
||||
}
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+id+"/messages?"+tc.query, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, tc.status, body)
|
||||
assertErrorCode(t, body, tc.code)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_MessageCursorScope rejects a continuation from another chat's history.
|
||||
func TestController_MessageCursorScope(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
first := chat(t, ctrl, actor)
|
||||
second := chat(t, ctrl, actor)
|
||||
path := "/api/v1/chats/" + first + "/messages"
|
||||
for _, text := range []string{"first", "second"} {
|
||||
call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": text}, http.StatusCreated)
|
||||
}
|
||||
page := call(t, ctrl, http.MethodGet, path+"?limit=1", actor, nil, http.StatusOK)
|
||||
token := page["next_cursor"].(string)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+second+"/messages?cursor="+url.QueryEscape(token), actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
}
|
||||
|
||||
// TestController_MessagePageLimitChange preserves continuation when the client changes page size.
|
||||
func TestController_MessagePageLimitChange(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
path := "/api/v1/chats/" + chat(t, ctrl, actor) + "/messages"
|
||||
for _, text := range []string{"first", "second", "third"} {
|
||||
call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": text}, http.StatusCreated)
|
||||
}
|
||||
first := call(t, ctrl, http.MethodGet, path+"?limit=1", actor, nil, http.StatusOK)
|
||||
token := first["next_cursor"].(string)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, path+"?limit=100&cursor="+url.QueryEscape(token), actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusOK, body)
|
||||
items := body["items"].([]any)
|
||||
if len(items) != 2 || body["next_cursor"] != nil {
|
||||
t.Fatalf("unexpected final page: %v", body)
|
||||
}
|
||||
if items[0].(map[string]any)["text"] != "second" || items[1].(map[string]any)["text"] != "third" {
|
||||
t.Fatalf("lost order or skipped messages: %v", items)
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_MessageCapacity preserves acknowledged data after rejecting an overflow write.
|
||||
func TestController_MessageCapacity(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.Memory.MaxMessages = 2
|
||||
})
|
||||
actor := user(t, ctrl)
|
||||
path := "/api/v1/chats/" + chat(t, ctrl, actor) + "/messages"
|
||||
first := call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": "first"}, http.StatusCreated)
|
||||
second := call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": "second"}, http.StatusCreated)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, path, actor, []byte(`{"text":"rejected"}`))
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusServiceUnavailable, body)
|
||||
assertErrorCode(t, body, "unavailable")
|
||||
items := history(t, ctrl, actor, path)
|
||||
if len(items) != 2 || items[0].(map[string]any)["id"] != first["id"] || items[1].(map[string]any)["id"] != second["id"] {
|
||||
t.Fatalf("overflow changed acknowledged messages: %v", items)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission"
|
||||
)
|
||||
|
||||
// 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())
|
||||
started := time.Now()
|
||||
err := ctx.Next()
|
||||
if err != nil {
|
||||
err = ctrl.handleErr(ctx, err)
|
||||
}
|
||||
ctrl.logRequest(ctx, time.Since(started))
|
||||
return err
|
||||
}
|
||||
|
||||
// logRequest logs request metadata without including message contents.
|
||||
func (ctrl *Controller) logRequest(ctx *fiber.Ctx, elapsed time.Duration) {
|
||||
route := "unmatched"
|
||||
if ctx.Route() != nil {
|
||||
route = ctx.Route().Path
|
||||
}
|
||||
ctrl.log.Info("http request",
|
||||
zap.String("method", ctx.Method()),
|
||||
zap.String("route", route),
|
||||
zap.Int("status", ctx.Response().StatusCode()),
|
||||
zap.String("request_id", ctx.GetRespHeader(headerRequestID)),
|
||||
zap.Duration("duration", elapsed),
|
||||
)
|
||||
}
|
||||
|
||||
// admit reserves global budgets and bounds downstream request work.
|
||||
func (ctrl *Controller) admit(ctx *fiber.Ctx) error {
|
||||
if ctrl.stopping.Load() {
|
||||
return errBusy
|
||||
}
|
||||
requestCtx, cancel := context.WithTimeout(ctx.UserContext(), ctrl.cfg.Timeout())
|
||||
defer cancel()
|
||||
ctx.SetUserContext(requestCtx)
|
||||
release, err := ctrl.admission.Enter(requestCtx, requestGroup(ctx), "")
|
||||
if err != nil {
|
||||
return admissionError(ctx, err)
|
||||
}
|
||||
defer release()
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
// requireIdentity resolves the session before reserving per-user budgets.
|
||||
func (ctrl *Controller) requireIdentity(ctx *fiber.Ctx) error {
|
||||
user, err := ctrl.auth.Authenticate(ctx.UserContext(), bearer(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx.Locals(identityKey, user)
|
||||
release, err := ctrl.admission.Enter(ctx.UserContext(), requestGroup(ctx), user)
|
||||
if err != nil {
|
||||
return admissionError(ctx, err)
|
||||
}
|
||||
defer release()
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
// admissionError maps policy rejection and backend failure into HTTP-owned errors.
|
||||
func admissionError(ctx *fiber.Ctx, err error) error {
|
||||
ctx.Set(fiber.HeaderRetryAfter, strconv.Itoa(retryAfterSeconds))
|
||||
if errors.Is(err, admission.ErrRate) {
|
||||
return errRateLimited
|
||||
}
|
||||
return errBusy
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
)
|
||||
|
||||
// TestController_InFlightAdmission checks rejection, recovery and health exemption independently.
|
||||
func TestController_InFlightAdmission(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
release bool
|
||||
path string
|
||||
status int
|
||||
}{
|
||||
{"Negative: occupied execution slot", false, "/api/v1/users/me", http.StatusServiceUnavailable},
|
||||
{"Positive: released execution slot", true, "/api/v1/users/me", http.StatusUnauthorized},
|
||||
{"Positive: health bypasses occupied slot", false, "/health/live", http.StatusOK},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.HTTP.Admission.MaxInFlight = 1
|
||||
})
|
||||
if !ctrl.admission.(*fixtureAdmission).Acquire() {
|
||||
t.Fatal("fixture could not reserve slot")
|
||||
}
|
||||
if tc.release {
|
||||
ctrl.admission.(*fixtureAdmission).Release()
|
||||
} else {
|
||||
t.Cleanup(ctrl.admission.(*fixtureAdmission).Release)
|
||||
}
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, tc.path, "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, tc.status, body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_RateAdmission checks exhausted tokens without timing-dependent HTTP setup.
|
||||
func TestController_RateAdmission(t *testing.T) {
|
||||
t.Run("/api/v1/users/me", func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.HTTP.Admission.RequestsPerSecond = 1
|
||||
cfg.HTTP.Admission.Burst = 1
|
||||
})
|
||||
if !ctrl.admission.(*fixtureAdmission).Allow(time.Now()) {
|
||||
t.Fatal("fixture token missing")
|
||||
}
|
||||
expected := http.StatusTooManyRequests
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, expected, body)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("/health/ready", func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.HTTP.Admission.RequestsPerSecond = 1
|
||||
cfg.HTTP.Admission.Burst = 1
|
||||
})
|
||||
if !ctrl.admission.(*fixtureAdmission).Allow(time.Now()) {
|
||||
t.Fatal("fixture token missing")
|
||||
}
|
||||
expected := http.StatusOK
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/health/ready", "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, expected, body)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_Draining checks each endpoint's admission policy during shutdown.
|
||||
func TestController_Draining(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
path string
|
||||
status int
|
||||
}{
|
||||
{"Negative: readiness disabled", "/health/ready", http.StatusServiceUnavailable},
|
||||
{"Positive: liveness remains available", "/health/live", http.StatusOK},
|
||||
{"Negative: business requests rejected", "/api/v1/users/me", http.StatusServiceUnavailable},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.stopping.Store(true)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, tc.path, "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, tc.status, body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_UnknownRoute checks the public fallback for an unmatched path.
|
||||
func TestController_UnknownRoute(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/missing", "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusNotFound, body)
|
||||
assertErrorCode(t, body, "not_found")
|
||||
}
|
||||
|
||||
// TestController_New rejects each missing dependency independently.
|
||||
func TestController_New(t *testing.T) {
|
||||
t.Run("Negative: missing configuration", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(fixture.log, nil, fixture.service, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing logger", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(nil, &fixture.cfg, fixture.service, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing service", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(fixture.log, &fixture.cfg, nil, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing registry", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(fixture.log, &fixture.cfg, fixture.service, nil, fixture.admission, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing limiter", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(fixture.log, &fixture.cfg, fixture.service, fixture.errorRegistry, nil, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"go.lab260.ru/fielderr"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
var (
|
||||
errBusy = publicFailure(codeUnavailable, "server is busy")
|
||||
errRateLimited = publicFailure(codeRateLimited, "request rate exceeded")
|
||||
errTooLarge = publicFailure(codeTooLarge, "request body is too large")
|
||||
errMedia = publicFailure(codeMedia, "expected application/json")
|
||||
errInternal = publicFailure(codeInternal, "internal server error")
|
||||
)
|
||||
|
||||
// publicFailure creates a transport-owned error with a safe API message.
|
||||
func publicFailure(code, message string) error {
|
||||
return fielderr.WithStatus(errors.New(message), fielderr.NewStatusCode(code), message)
|
||||
}
|
||||
|
||||
// publicError maps application failures into the public API envelope.
|
||||
// Unknown errors receive a fixed response without exposing their details.
|
||||
func publicError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrUnavailable):
|
||||
return publicFailure(codeUnavailable, "dependency unavailable")
|
||||
case errors.Is(err, service.ErrInvalid):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeInvalid), "invalid request")
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeUnauthorized), "unknown user identity")
|
||||
case errors.Is(err, service.ErrNotFound):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeNotFound), "resource not found")
|
||||
case errors.Is(err, service.ErrConflict):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeConflict), "username already exists")
|
||||
case errors.Is(err, service.ErrCapacity):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeUnavailable), "in-memory storage capacity reached")
|
||||
case errors.Is(err, errBusy):
|
||||
return errBusy
|
||||
case errors.Is(err, errRateLimited):
|
||||
return errRateLimited
|
||||
case errors.Is(err, errTooLarge):
|
||||
return errTooLarge
|
||||
case errors.Is(err, errMedia):
|
||||
return errMedia
|
||||
default:
|
||||
return errInternal
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"go.lab260.ru/fielderr"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// TestPublicErrorSafety maps wrapped application failures without exposing internal details.
|
||||
func TestPublicErrorSafety(t *testing.T) {
|
||||
t.Run("wrapped application error", func(t *testing.T) {
|
||||
err := publicError(fmt.Errorf("private database detail: %w", service.ErrConflict))
|
||||
response := errorResponse(err, "request")
|
||||
if response.Error.Code != codeConflict || response.Error.Message != "username already exists" {
|
||||
t.Fatalf("unexpected response: %+v", response)
|
||||
}
|
||||
})
|
||||
t.Run("unknown error", func(t *testing.T) {
|
||||
err := publicError(errors.New("private database detail"))
|
||||
if err != errInternal {
|
||||
t.Fatalf("unexpected public error: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("foreign public status", func(t *testing.T) {
|
||||
err := fielderr.WithStatus(errors.New("private detail"), fielderr.NewStatusCode(codeInvalid), "private detail")
|
||||
if publicError(err) != errInternal {
|
||||
t.Fatal("untrusted error metadata reached the public response")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestPublicErrorUnavailable keeps dependency details out of the public envelope.
|
||||
func TestPublicErrorUnavailable(t *testing.T) {
|
||||
err := publicError(fmt.Errorf("private database detail: %w", service.ErrUnavailable))
|
||||
response := errorResponse(err, "request")
|
||||
if response.Error.Code != codeUnavailable || response.Error.Message != "dependency unavailable" {
|
||||
t.Fatalf("unexpected response: %+v", response)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package fiber
|
||||
|
||||
// initRoutes registers health endpoints and authenticated application routes.
|
||||
func (ctrl *Controller) initRoutes() {
|
||||
ctrl.server.Get("/health/live", ctrl.handleLive)
|
||||
ctrl.server.Get("/health/ready", ctrl.handleReady)
|
||||
ctrl.server.Use(ctrl.admit)
|
||||
ctrl.server.Post("/api/v1/users", ctrl.HandleUsersCreate)
|
||||
|
||||
ctrl.server.Post("/api/v1/auth/sessions", ctrl.HandleLogin)
|
||||
|
||||
api := ctrl.server.Group("/api/v1", ctrl.requireIdentity)
|
||||
api.Delete("/auth/sessions/current", ctrl.HandleLogout)
|
||||
api.Get("/users/me", ctrl.HandleUsersGetMe)
|
||||
api.Post("/chats", ctrl.HandleChatsCreate)
|
||||
api.Get("/chats", ctrl.HandleChatsGetPage)
|
||||
api.Get("/chats/:chat_id", ctrl.HandleChatsGetByID)
|
||||
api.Post("/chats/:chat_id/messages", ctrl.HandleMessagesCreate)
|
||||
api.Get("/chats/:chat_id/messages", ctrl.HandleMessagesGetPage)
|
||||
|
||||
ctrl.server.Use(ctrl.handleNotFound)
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// TestController_UsersCreate checks one registration contract scenario per subtest.
|
||||
func TestController_UsersCreate(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
status int
|
||||
}{
|
||||
{"Positive: valid Unicode display name", `{"password":"fixture-password-123","username":"alice","display_name":"Алиса 👋"}`, http.StatusCreated},
|
||||
{"Positive: display name at rune limit", `{"password":"fixture-password-123","username":"alice","display_name":"` + strings.Repeat("👋", 100) + `"}`, http.StatusCreated},
|
||||
{"Negative: display name exceeds rune limit", `{"password":"fixture-password-123","username":"alice","display_name":"` + strings.Repeat("👋", 101) + `"}`, http.StatusBadRequest},
|
||||
{"Negative: uppercase username", `{"password":"fixture-password-123","username":"Alice","display_name":"Alice"}`, http.StatusBadRequest},
|
||||
{"Negative: malformed JSON", `{`, http.StatusBadRequest},
|
||||
{"Negative: null root", `null`, http.StatusBadRequest},
|
||||
{"Negative: array root", `[]`, http.StatusBadRequest},
|
||||
{"Negative: missing fields", `{}`, http.StatusBadRequest},
|
||||
{"Negative: null field", `{"password":"fixture-password-123","username":"alice","display_name":null}`, http.StatusBadRequest},
|
||||
{"Negative: wrong field type", `{"password":"fixture-password-123","username":5,"display_name":"Alice"}`, http.StatusBadRequest},
|
||||
{"Negative: unknown field", `{"password":"fixture-password-123","username":"alice","display_name":"Alice","unknown":"secret"}`, http.StatusBadRequest},
|
||||
{"Negative: field name case", `{"password":"fixture-password-123","Username":"alice","display_name":"Alice"}`, http.StatusBadRequest},
|
||||
{"Negative: duplicate field", `{"password":"fixture-password-123","username":"alice","username":"bob","display_name":"Alice"}`, http.StatusBadRequest},
|
||||
{"Negative: trailing object", `{"password":"fixture-password-123","username":"alice","display_name":"Alice"} {}`, http.StatusBadRequest},
|
||||
{"Negative: invalid UTF-8", "{\"username\":\"alice\",\"display_name\":\"\xff\"}", http.StatusBadRequest},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/users", "", []byte(tc.body))
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, tc.status, body)
|
||||
if tc.status == http.StatusBadRequest {
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
return
|
||||
}
|
||||
if body["username"] != "alice" || body["display_name"] == "" {
|
||||
t.Fatalf("registration fields changed: %v", body)
|
||||
}
|
||||
if _, err := uuid.Parse(body["id"].(string)); err != nil {
|
||||
t.Fatalf("invalid assigned ID: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_UsersGetMe verifies profile selection and authentication failures.
|
||||
func TestController_UsersGetMe(t *testing.T) {
|
||||
t.Run("Positive: own profile", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
identity := actor
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusOK, body)
|
||||
if body["id"] != actor || body["display_name"] != "Алиса 👋" {
|
||||
t.Fatalf("wrong profile: %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing identity", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
identity := ""
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown identity", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
identity := uuid.NewString()
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
})
|
||||
}
|
||||
|
||||
// assertHTTPStatus reports the response body alongside a mismatched status.
|
||||
func assertHTTPStatus(t *testing.T, got, want int, body map[string]any) {
|
||||
t.Helper()
|
||||
if got != want {
|
||||
t.Fatalf("status=%d, want=%d, body=%v", got, want, body)
|
||||
}
|
||||
}
|
||||
|
||||
// assertErrorCode checks the documented error classification independently of status.
|
||||
func assertErrorCode(t *testing.T, body map[string]any, want string) {
|
||||
t.Helper()
|
||||
envelope, ok := body["error"].(map[string]any)
|
||||
if !ok || envelope["code"] != want {
|
||||
t.Fatalf("error=%v, want code %q", body, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Package controller connects transport lifecycles to Fx.
|
||||
package controller
|
||||
|
||||
import "context"
|
||||
|
||||
// Controller is a process-owned transport server.
|
||||
type Controller interface {
|
||||
// Start acquires the listener and reports startup errors to the lifecycle owner.
|
||||
Start(context.Context) error
|
||||
// Stop stops accepting work and drains active requests within the supplied deadline.
|
||||
Stop(context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Package cursor signs and verifies resource-bound keyset positions.
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
cursorSigningKeyBytes = 32
|
||||
maxEncodedCursorBytes = 1024
|
||||
)
|
||||
|
||||
// ErrInvalid means a cursor is malformed, tampered with or bound to another resource.
|
||||
var ErrInvalid = errors.New("invalid cursor")
|
||||
|
||||
// Position identifies the last record already returned by keyset pagination.
|
||||
type Position struct {
|
||||
// CreatedAt is the creation timestamp of the last returned record.
|
||||
CreatedAt time.Time
|
||||
// ID breaks ties between records sharing a timestamp.
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// Codec authenticates pagination positions with an immutable process-local key.
|
||||
type Codec struct {
|
||||
key [cursorSigningKeyBytes]byte
|
||||
}
|
||||
|
||||
type cursorPayload struct {
|
||||
// Resource binds the position to a chat history or one user's chat list.
|
||||
Resource string `json:"r"`
|
||||
// Time is the creation timestamp of the last record in the previous page.
|
||||
Time time.Time `json:"t"`
|
||||
// ID breaks ties between records with the same creation timestamp.
|
||||
ID uuid.UUID `json:"i"`
|
||||
}
|
||||
|
||||
// New creates a cursor codec with a random process-local signing key.
|
||||
func New() (*Codec, error) {
|
||||
codec := &Codec{}
|
||||
if _, err := rand.Read(codec.key[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return codec, nil
|
||||
}
|
||||
|
||||
// Encode serializes and signs a pagination position bound to a resource.
|
||||
func (codec *Codec) Encode(resource string, position Position) (string, error) {
|
||||
payload, err := json.Marshal(cursorPayload{
|
||||
Resource: resource,
|
||||
Time: position.CreatedAt,
|
||||
ID: position.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encode cursor: %w", err)
|
||||
}
|
||||
payload = append(payload, codec.signature(payload)...)
|
||||
return base64.RawURLEncoding.EncodeToString(payload), nil
|
||||
}
|
||||
|
||||
// Decode verifies the cursor signature and extracts its resource-bound position.
|
||||
func (codec *Codec) Decode(encoded, resource string) (Position, error) {
|
||||
if encoded == "" {
|
||||
return Position{}, nil
|
||||
}
|
||||
if len(encoded) > maxEncodedCursorBytes {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
signed, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil || len(signed) <= sha256.Size {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
boundary := len(signed) - sha256.Size
|
||||
payload, signature := signed[:boundary], signed[boundary:]
|
||||
if !hmac.Equal(signature, codec.signature(payload)) {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
return decodeCursorPosition(payload, resource)
|
||||
}
|
||||
|
||||
// signature computes the HMAC-SHA256 authentication tag for a cursor payload.
|
||||
func (codec *Codec) signature(payload []byte) []byte {
|
||||
mac := hmac.New(sha256.New, codec.key[:])
|
||||
// hash.Hash.Write is documented to always return a nil error.
|
||||
_, _ = mac.Write(payload)
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
|
||||
// decodeCursorPosition validates the decoded cursor resource and timestamp.
|
||||
func decodeCursorPosition(payload []byte, resource string) (Position, error) {
|
||||
var cursor cursorPayload
|
||||
if err := json.Unmarshal(payload, &cursor); err != nil {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
if cursor.Resource != resource || cursor.Time.IsZero() {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
return Position{CreatedAt: cursor.Time, ID: cursor.ID}, nil
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// TestCodec_EncodeDecode preserves the complete position through an authenticated round trip.
|
||||
func TestCodec_EncodeDecode(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
position := Position{CreatedAt: time.Unix(1700000000, 123456789).UTC(), ID: uuid.New()}
|
||||
|
||||
// Act.
|
||||
encoded, err := codec.Encode("chats:alice", position)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if encoded == "" {
|
||||
t.Fatal("encoded position is empty")
|
||||
}
|
||||
decoded, err := codec.Decode(encoded, "chats:alice")
|
||||
if err != nil || decoded != position {
|
||||
t.Fatalf("decoded=%v, want=%v, error=%v", decoded, position, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCodec_Decode checks first-page behavior and independent rejection conditions.
|
||||
func TestCodec_Decode(t *testing.T) {
|
||||
t.Run("Positive: empty token starts first page", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode("", "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if err != nil || got != (Position{}) {
|
||||
t.Fatalf("first-page position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: another resource", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := encodeFixture(t, codec, "chats:alice")
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:bob")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: another process key", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := encodeFixture(t, codec, "chats:alice")
|
||||
codec = newTestCodec(t)
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: tampered payload", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := encodeFixture(t, codec, "chats:alice")
|
||||
signed, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signed[0] ^= 1
|
||||
encoded = base64.RawURLEncoding.EncodeToString(signed)
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: oversized token", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := strings.Repeat("a", 1025)
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed base64", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := "!invalid!"
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: signed malformed JSON", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := signedPayload(codec, []byte("not JSON"))
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: signed zero timestamp", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := signedPayload(codec, []byte(`{"r":"chats:alice","t":"0001-01-01T00:00:00Z","i":"11111111-1111-1111-1111-111111111111"}`))
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// signedPayload creates authenticated malformed fixtures to isolate payload validation.
|
||||
func signedPayload(codec *Codec, payload []byte) string {
|
||||
return base64.RawURLEncoding.EncodeToString(append(payload, codec.signature(payload)...))
|
||||
}
|
||||
|
||||
// newTestCodec creates an independent signing key for one scenario.
|
||||
func newTestCodec(t *testing.T) *Codec {
|
||||
t.Helper()
|
||||
codec, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return codec
|
||||
}
|
||||
|
||||
// encodeFixture prepares a valid token before testing a separate decoding condition.
|
||||
func encodeFixture(t *testing.T, codec *Codec, resource string) string {
|
||||
t.Helper()
|
||||
token, err := codec.Encode(resource, Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Package hashring implements immutable consistent hashing with virtual nodes.
|
||||
package hashring
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type point struct {
|
||||
hash uint64
|
||||
node string
|
||||
}
|
||||
|
||||
// Ring maps arbitrary keys to stable node identifiers.
|
||||
type Ring struct {
|
||||
points []point
|
||||
}
|
||||
|
||||
// New creates an order-independent ring and rejects ambiguous node identities.
|
||||
func New(nodes []string, replicas int) (*Ring, error) {
|
||||
if len(nodes) == 0 || replicas < 1 {
|
||||
return nil, fmt.Errorf("nodes and positive virtual node count are required")
|
||||
}
|
||||
ring := &Ring{}
|
||||
seen := make(map[string]bool)
|
||||
for _, node := range nodes {
|
||||
if node == "" || seen[node] {
|
||||
return nil, fmt.Errorf("node identifiers must be unique and nonempty")
|
||||
}
|
||||
seen[node] = true
|
||||
for index := range replicas {
|
||||
ring.points = append(ring.points, point{hash: hash(node + ":" + strconv.Itoa(index)), node: node})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(ring.points, func(a, b point) int {
|
||||
if order := cmp.Compare(a.hash, b.hash); order != 0 {
|
||||
return order
|
||||
}
|
||||
return cmp.Compare(a.node, b.node)
|
||||
})
|
||||
return ring, nil
|
||||
}
|
||||
|
||||
// Owner selects the first virtual node clockwise from the key hash.
|
||||
func (r *Ring) Owner(key string) string {
|
||||
value := hash(key)
|
||||
index := sort.Search(len(r.points), func(index int) bool {
|
||||
return r.points[index].hash >= value
|
||||
})
|
||||
return r.points[index%len(r.points)].node
|
||||
}
|
||||
|
||||
// hash maps a stable string into the ring's 64-bit coordinate space.
|
||||
func hash(value string) uint64 {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return binary.BigEndian.Uint64(sum[:8])
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package hashring
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestExpansionMovesOnlyKeysOwnedByNewNode verifies the consistent hashing invariant.
|
||||
func TestExpansionMovesOnlyKeysOwnedByNewNode(t *testing.T) {
|
||||
before, err := New([]string{"a", "b"}, 256)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := New([]string{"c", "b", "a"}, 256)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
moved := 0
|
||||
for index := range 100000 {
|
||||
key := fmt.Sprint(index)
|
||||
oldOwner, newOwner := before.Owner(key), after.Owner(key)
|
||||
if oldOwner != newOwner {
|
||||
moved++
|
||||
if newOwner != "c" {
|
||||
t.Fatalf("existing nodes exchanged key %s", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
fraction := float64(moved) / 100000
|
||||
if fraction < 0.2 || fraction > 0.45 {
|
||||
t.Fatalf("unexpected moved fraction: %f", fraction)
|
||||
}
|
||||
t.Logf("100000 keys: moved=%d fraction=%.5f", moved, fraction)
|
||||
}
|
||||
|
||||
// TestRingRejectsAmbiguousConfiguration checks independent malformed rings.
|
||||
func TestRingRejectsAmbiguousConfiguration(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
nodes []string
|
||||
replicas int
|
||||
}{
|
||||
{"empty", nil, 1},
|
||||
{"zero replicas", []string{"a"}, 0},
|
||||
{"empty node", []string{""}, 1},
|
||||
{"duplicate", []string{"a", "a"}, 1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := New(tc.nodes, tc.replicas); err == nil {
|
||||
t.Fatal("invalid ring accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRingIgnoresInputOrder verifies that replicas agree despite configuration ordering.
|
||||
func TestRingIgnoresInputOrder(t *testing.T) {
|
||||
a, err := New([]string{"a", "b"}, 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := New([]string{"b", "a"}, 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index := range 1000 {
|
||||
key := fmt.Sprint(index)
|
||||
if a.Owner(key) != b.Owner(key) {
|
||||
t.Fatal("node order changes ownership")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Package dto defines the transport-independent data shared by service and store.
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// UserDTO is the public account profile without credentials.
|
||||
type UserDTO struct {
|
||||
// ID is the server-generated user identifier.
|
||||
ID uuid.UUID
|
||||
// Username is the unique lowercase ASCII account name.
|
||||
Username string
|
||||
// DisplayName is the display label, limited to 100 Unicode code points.
|
||||
DisplayName string
|
||||
// CreatedAt is the server-assigned UTC creation time.
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// ChatDTO is a chat with immutable membership.
|
||||
type ChatDTO struct {
|
||||
// ID is the server-generated chat identifier.
|
||||
ID uuid.UUID
|
||||
// Title is the nonblank title, limited to 100 Unicode code points.
|
||||
Title string
|
||||
// MemberIDs contains the fixed set of users allowed to read and write the chat.
|
||||
MemberIDs []uuid.UUID
|
||||
// CreatedAt is the server-assigned UTC creation time.
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// MessageDTO is an immutable message stored in a chat.
|
||||
type MessageDTO struct {
|
||||
// ID is the server-generated message identifier.
|
||||
ID uuid.UUID
|
||||
// ChatID identifies the owning chat.
|
||||
ChatID uuid.UUID
|
||||
// SenderID identifies the user resolved from the request identity.
|
||||
SenderID uuid.UUID
|
||||
// Text contains the original text, limited to 4000 Unicode code points.
|
||||
Text string
|
||||
// CreatedAt is the server-assigned UTC ordering timestamp.
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// UsersCreateRequestDTO carries untrusted registration values into the service.
|
||||
type UsersCreateRequestDTO struct {
|
||||
// Username is the raw requested account name.
|
||||
Username string
|
||||
// DisplayName is the raw requested display label.
|
||||
DisplayName string
|
||||
}
|
||||
|
||||
// ChatsCreateRequestDTO carries untrusted chat creation input.
|
||||
type ChatsCreateRequestDTO struct {
|
||||
// UserID is the caller identifier resolved from a validated session.
|
||||
UserID string
|
||||
// Title is the raw requested chat title.
|
||||
Title string
|
||||
// MemberIDs contains raw user UUIDs; the service checks uniqueness and membership.
|
||||
MemberIDs []string
|
||||
}
|
||||
|
||||
// MessagesCreateRequestDTO carries untrusted message creation input.
|
||||
type MessagesCreateRequestDTO struct {
|
||||
// UserID is the authenticated caller identifier, never a supplied sender field.
|
||||
UserID string
|
||||
// ChatID is the raw chat UUID from the route.
|
||||
ChatID string
|
||||
// Text is the unmodified message text to validate.
|
||||
Text string
|
||||
}
|
||||
|
||||
// PageRequestDTO carries raw pagination values for service-level validation.
|
||||
type PageRequestDTO struct {
|
||||
// UserID is the caller identifier resolved from a validated session.
|
||||
UserID string
|
||||
// ChatID is the requested chat UUID; it is unused when listing chats.
|
||||
ChatID string
|
||||
// Limit is the raw page size; empty selects the contract default.
|
||||
Limit string
|
||||
// Cursor is the opaque continuation token; empty starts at the beginning.
|
||||
Cursor string
|
||||
}
|
||||
|
||||
// PositionDTO is a validated keyset boundary; its zero value starts a history.
|
||||
type PositionDTO struct {
|
||||
// CreatedAt is the timestamp of the last record already returned.
|
||||
CreatedAt time.Time
|
||||
// ID is the tie-breaking identifier of the last record already returned.
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// ChatPageDTO contains an ordered page of accessible chats.
|
||||
type ChatPageDTO struct {
|
||||
// Items contains at most the requested number of chats.
|
||||
Items []ChatDTO
|
||||
// NextCursor continues the same user-specific list; nil marks its current end.
|
||||
NextCursor *string
|
||||
}
|
||||
|
||||
// MessagePageDTO contains an ordered page of chat history.
|
||||
type MessagePageDTO struct {
|
||||
// Items contains at most the requested number of messages.
|
||||
Items []MessageDTO
|
||||
// NextCursor continues the same chat history; nil marks its current end.
|
||||
NextCursor *string
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// SessionDTO is an issued session, exposing the raw token only at creation.
|
||||
type SessionDTO struct {
|
||||
// Token contains 256 random bits encoded for a Bearer header.
|
||||
Token string
|
||||
// ExpiresAt is an absolute UTC deadline which is not extended by reads.
|
||||
ExpiresAt time.Time
|
||||
// User is the authenticated account without credentials.
|
||||
User UserDTO
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Package http defines the public JSON boundary, separate from DTOs.
|
||||
package http
|
||||
|
||||
import "time"
|
||||
|
||||
// UsersCreateRequest is the registration payload.
|
||||
type UsersCreateRequest struct {
|
||||
// Password is the unmodified Unicode registration secret.
|
||||
Password string `json:"password"`
|
||||
// Username is the unique lowercase ASCII username.
|
||||
Username string `json:"username"`
|
||||
// DisplayName is the user-visible name, limited to 100 Unicode code points.
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
// ChatsCreateRequest is the chat payload.
|
||||
type ChatsCreateRequest struct {
|
||||
// Title is the nonblank chat title, limited to 100 Unicode code points.
|
||||
Title string `json:"title"`
|
||||
// MemberIDs contains unique user UUIDs, including the caller when creating a chat.
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
// MessagesCreateRequest is the message payload.
|
||||
type MessagesCreateRequest struct {
|
||||
// Text contains nonblank text, limited to 4000 Unicode code points.
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// UserResponse is the public user model.
|
||||
type UserResponse struct {
|
||||
// ID is the canonical server-generated UUID.
|
||||
ID string `json:"id"`
|
||||
// Username is the unique lowercase ASCII username.
|
||||
Username string `json:"username"`
|
||||
// DisplayName is the user-visible name, limited to 100 Unicode code points.
|
||||
DisplayName string `json:"display_name"`
|
||||
// CreatedAt is the UTC creation time serialized as RFC 3339.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ChatResponse is the public chat model.
|
||||
type ChatResponse struct {
|
||||
// ID is the canonical server-generated UUID.
|
||||
ID string `json:"id"`
|
||||
// Title is the nonblank chat title, limited to 100 Unicode code points.
|
||||
Title string `json:"title"`
|
||||
// MemberIDs contains unique user UUIDs, including the caller when creating a chat.
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
// CreatedAt is the UTC creation time serialized as RFC 3339.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// MessageResponse is the public message model.
|
||||
type MessageResponse struct {
|
||||
// ID is the canonical server-generated UUID.
|
||||
ID string `json:"id"`
|
||||
// ChatID is the canonical UUID of the chat containing the message.
|
||||
ChatID string `json:"chat_id"`
|
||||
// SenderID is derived from the request identity, never from a client-supplied sender.
|
||||
SenderID string `json:"sender_id"`
|
||||
// Text contains nonblank text, limited to 4000 Unicode code points.
|
||||
Text string `json:"text"`
|
||||
// CreatedAt is the UTC creation time serialized as RFC 3339.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ChatPageResponse contains visible chats.
|
||||
type ChatPageResponse struct {
|
||||
// Items contains the ordered page records; an empty page is serialized as an empty array.
|
||||
Items []ChatResponse `json:"items"`
|
||||
// NextCursor is the opaque continuation token or null when the current page is last.
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// MessagePageResponse contains the requested history page.
|
||||
type MessagePageResponse struct {
|
||||
// Items contains the ordered page records; an empty page is serialized as an empty array.
|
||||
Items []MessageResponse `json:"items"`
|
||||
// NextCursor is the opaque continuation token or null when the current page is last.
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// ErrorResponse is the mandatory error envelope.
|
||||
type ErrorResponse struct {
|
||||
// Error contains the safe public error details.
|
||||
Error ErrorDetail `json:"error"`
|
||||
}
|
||||
|
||||
// ErrorDetail never exposes internal errors or input contents.
|
||||
type ErrorDetail struct {
|
||||
// Code is one of the machine-readable error codes declared by the API contract.
|
||||
Code string `json:"code"`
|
||||
// Message is a safe public explanation without internal errors or input contents.
|
||||
Message string `json:"message"`
|
||||
// RequestID matches the X-Request-Id response header for log correlation.
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Package password implements a bounded Argon2id password KDF.
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
memoryKiB = 19 * 1024
|
||||
iterations = 2
|
||||
parallelism = 1
|
||||
saltBytes = 16
|
||||
hashBytes = 32
|
||||
prefix = "$argon2id$v=19$m=19456,t=2,p=1$"
|
||||
)
|
||||
|
||||
// Hasher implements password hashing without transport or storage dependencies.
|
||||
type Hasher struct{}
|
||||
|
||||
// Hash generates a salted Argon2id encoding using fixed resource bounds.
|
||||
func (Hasher) Hash(password string) (string, error) {
|
||||
salt := make([]byte, saltBytes)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, iterations, memoryKiB, parallelism, hashBytes)
|
||||
return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash), nil
|
||||
}
|
||||
|
||||
// Verify accepts only this application's bounded KDF encoding and compares in constant time.
|
||||
func (Hasher) Verify(encoded, password string) bool {
|
||||
if !strings.HasPrefix(encoded, prefix) {
|
||||
return false
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$")
|
||||
if len(parts) != 2 {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[0])
|
||||
if err != nil || len(salt) != saltBytes {
|
||||
return false
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||||
if err != nil || len(expected) != hashBytes {
|
||||
return false
|
||||
}
|
||||
actual := argon2.IDKey([]byte(password), salt, iterations, memoryKiB, parallelism, hashBytes)
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPasswordRoundTrip verifies long Unicode input without bcrypt-style truncation.
|
||||
func TestPasswordRoundTrip(t *testing.T) {
|
||||
password := strings.Repeat("🔐", 128)
|
||||
hasher := Hasher{}
|
||||
encoded, err := hasher.Hash(password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !hasher.Verify(encoded, password) || hasher.Verify(encoded, password+"x") {
|
||||
t.Fatal("password verification mismatch")
|
||||
}
|
||||
second, err := hasher.Hash(password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if encoded == second {
|
||||
t.Fatal("salt reused")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPasswordRejectsInvalidEncoding checks corrupt or unbounded KDF descriptions.
|
||||
func TestPasswordRejectsInvalidEncoding(t *testing.T) {
|
||||
for _, encoded := range []string{"", "$argon2id$v=19$m=999999999,t=2,p=1$a$b", prefix + "x", prefix + "%%%$abc", prefix + "YWJj$abc", prefix + "AAAAAAAAAAAAAAAAAAAAAA$%%%", prefix + "AAAAAAAAAAAAAAAAAAAAAA$YWJj"} {
|
||||
t.Run(encoded, func(t *testing.T) {
|
||||
if (Hasher{}).Verify(encoded, "password") {
|
||||
t.Fatal("invalid encoding accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// Passwords is the password KDF boundary used by authentication.
|
||||
type Passwords interface {
|
||||
// Hash creates a salted password encoding.
|
||||
Hash(password string) (string, error)
|
||||
// Verify checks the supplied password against its encoding.
|
||||
Verify(encoded, password string) bool
|
||||
}
|
||||
|
||||
// Accounts persists credentials and session validity independently of HTTP.
|
||||
type Accounts interface {
|
||||
// Register atomically stores a profile with credentials.
|
||||
Register(context.Context, dto.UserDTO, string) (dto.UserDTO, error)
|
||||
// Credentials looks up the password encoding and account profile.
|
||||
Credentials(context.Context, string) (dto.UserDTO, string, error)
|
||||
// SaveSession persists an opaque token digest and absolute expiry.
|
||||
SaveSession(context.Context, string, uuid.UUID, time.Time) error
|
||||
// SessionUser resolves an unexpired token digest.
|
||||
SessionUser(context.Context, string) (uuid.UUID, error)
|
||||
// RevokeSession invalidates a token digest.
|
||||
RevokeSession(context.Context, string) error
|
||||
}
|
||||
|
||||
// Authentication defines registration and opaque session operations.
|
||||
type Authentication interface {
|
||||
// Register validates registration and persists a password-protected account.
|
||||
Register(context.Context, dto.UsersCreateRequestDTO, string) (dto.UserDTO, error)
|
||||
// Login verifies credentials and issues an opaque session.
|
||||
Login(context.Context, string, string) (dto.SessionDTO, error)
|
||||
// Authenticate resolves a valid token to its immutable owner.
|
||||
Authenticate(context.Context, string) (string, error)
|
||||
// Logout revokes the current token.
|
||||
Logout(context.Context, string) error
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Package authentication validates credentials and owns the session lifecycle.
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"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"
|
||||
)
|
||||
|
||||
const (
|
||||
minimumPasswordRunes = 12
|
||||
maximumPasswordRunes = 128
|
||||
tokenBytes = 32
|
||||
)
|
||||
|
||||
// Service performs password and session operations through explicit boundaries.
|
||||
type Service struct {
|
||||
accounts service.Accounts
|
||||
passwords service.Passwords
|
||||
ttl time.Duration
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
// New validates dependencies and prepares the unknown-account verification hash.
|
||||
func New(accounts service.Accounts, passwords service.Passwords, ttl time.Duration) (*Service, error) {
|
||||
if accounts == nil || passwords == nil || ttl <= 0 {
|
||||
return nil, fmt.Errorf("accounts, passwords and positive session TTL are required")
|
||||
}
|
||||
dummyHash, err := passwords.Hash("unknown-account-dummy-password")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Service{accounts: accounts, passwords: passwords, ttl: ttl, dummyHash: dummyHash}, nil
|
||||
}
|
||||
|
||||
// Register checks profile and Unicode password bounds before hashing and persistence.
|
||||
func (s *Service) Register(ctx context.Context, request dto.UsersCreateRequestDTO, password string) (dto.UserDTO, error) {
|
||||
user, err := production.PrepareUser(request)
|
||||
if err != nil || !validPassword(password) {
|
||||
return dto.UserDTO{}, service.ErrInvalid
|
||||
}
|
||||
hash, err := s.passwords.Hash(password)
|
||||
if err != nil {
|
||||
return dto.UserDTO{}, err
|
||||
}
|
||||
user, err = s.accounts.Register(ctx, user, hash)
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
return dto.UserDTO{}, service.ErrConflict
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
// Login verifies credentials uniformly and persists a new session before returning its token.
|
||||
func (s *Service) Login(ctx context.Context, username, password string) (dto.SessionDTO, error) {
|
||||
if !validPassword(password) {
|
||||
return dto.SessionDTO{}, service.ErrUnauthorized
|
||||
}
|
||||
user, hash, err := s.accounts.Credentials(ctx, username)
|
||||
if err != nil && !errors.Is(err, store.ErrNotFound) {
|
||||
return dto.SessionDTO{}, err
|
||||
}
|
||||
missing := errors.Is(err, store.ErrNotFound)
|
||||
if missing {
|
||||
hash = s.dummyHash
|
||||
}
|
||||
if !s.passwords.Verify(hash, password) || missing {
|
||||
return dto.SessionDTO{}, service.ErrUnauthorized
|
||||
}
|
||||
random := make([]byte, tokenBytes)
|
||||
if _, err := rand.Read(random); err != nil {
|
||||
return dto.SessionDTO{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(random)
|
||||
expiry := time.Now().UTC().Add(s.ttl)
|
||||
if err := s.accounts.SaveSession(ctx, digest(token), user.ID, expiry); err != nil {
|
||||
return dto.SessionDTO{}, err
|
||||
}
|
||||
return dto.SessionDTO{Token: token, ExpiresAt: expiry, User: user}, nil
|
||||
}
|
||||
|
||||
// Authenticate checks absolute expiry in the source of truth on every request.
|
||||
func (s *Service) Authenticate(ctx context.Context, token string) (string, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(decoded) != tokenBytes {
|
||||
return "", service.ErrUnauthorized
|
||||
}
|
||||
id, err := s.accounts.SessionUser(ctx, digest(token))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return "", service.ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
// Logout removes the current session from the authoritative store.
|
||||
func (s *Service) Logout(ctx context.Context, token string) error {
|
||||
return s.accounts.RevokeSession(ctx, digest(token))
|
||||
}
|
||||
|
||||
// digest produces the storage key without persisting the bearer secret.
|
||||
func digest(token string) string {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// validPassword enforces the contract in Unicode code points without truncation.
|
||||
func validPassword(password string) bool {
|
||||
count := utf8.RuneCountInString(password)
|
||||
return utf8.ValidString(password) && count >= minimumPasswordRunes && count <= maximumPasswordRunes
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
type accountFixture struct {
|
||||
user dto.UserDTO
|
||||
hash string
|
||||
tokenHash string
|
||||
expiry time.Time
|
||||
failure error
|
||||
registerFailure error
|
||||
saveFailure error
|
||||
}
|
||||
|
||||
// Register captures one synthetic account or a prescribed persistence failure.
|
||||
func (f *accountFixture) Register(_ context.Context, user dto.UserDTO, hash string) (dto.UserDTO, error) {
|
||||
f.user = user
|
||||
f.hash = hash
|
||||
return user, f.registerFailure
|
||||
}
|
||||
|
||||
// Credentials returns the fixture account and its password encoding.
|
||||
func (f *accountFixture) Credentials(context.Context, string) (dto.UserDTO, string, error) {
|
||||
return f.user, f.hash, f.failure
|
||||
}
|
||||
|
||||
// SaveSession captures the digest and absolute expiry without storing the raw token.
|
||||
func (f *accountFixture) SaveSession(_ context.Context, hash string, _ uuid.UUID, expiry time.Time) error {
|
||||
f.tokenHash = hash
|
||||
f.expiry = expiry
|
||||
return f.saveFailure
|
||||
}
|
||||
|
||||
// SessionUser implements expiry and revocation for the service unit fixture.
|
||||
func (f *accountFixture) SessionUser(_ context.Context, hash string) (uuid.UUID, error) {
|
||||
if f.failure != nil {
|
||||
return uuid.Nil, f.failure
|
||||
}
|
||||
if hash != f.tokenHash || !f.expiry.After(time.Now()) {
|
||||
return uuid.Nil, store.ErrNotFound
|
||||
}
|
||||
return f.user.ID, nil
|
||||
}
|
||||
|
||||
// RevokeSession invalidates the fixture digest.
|
||||
func (f *accountFixture) RevokeSession(context.Context, string) error {
|
||||
f.tokenHash = ""
|
||||
return f.failure
|
||||
}
|
||||
|
||||
type passwordFixture struct {
|
||||
failure error
|
||||
}
|
||||
|
||||
// Hash creates an intentionally noncryptographic encoding for service-only unit tests.
|
||||
func (f passwordFixture) Hash(password string) (string, error) {
|
||||
return "fixture:" + password, f.failure
|
||||
}
|
||||
|
||||
// Verify compares only test fixture encodings; production uses Argon2id.
|
||||
func (passwordFixture) Verify(encoded, password string) bool {
|
||||
return encoded == "fixture:"+password
|
||||
}
|
||||
|
||||
// authFixture assembles deterministic service boundaries.
|
||||
func authFixture(t *testing.T) (*Service, *accountFixture) {
|
||||
t.Helper()
|
||||
accounts := &accountFixture{user: dto.UserDTO{ID: uuid.New(), Username: "alice"}, hash: "fixture:synthetic-password"}
|
||||
s, err := New(accounts, passwordFixture{}, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, accounts
|
||||
}
|
||||
|
||||
// TestRegisterValidatesPassword checks contract boundaries without truncation.
|
||||
func TestRegisterValidatesPassword(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
password string
|
||||
valid bool
|
||||
}{
|
||||
{"short", "short", false},
|
||||
{"minimum", strings.Repeat("a", 12), true},
|
||||
{"unicode maximum", strings.Repeat("🔐", 128), true},
|
||||
{"too long", strings.Repeat("a", 129), false},
|
||||
{"invalid UTF8", strings.Repeat("a", 12) + "\xff", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, _ := authFixture(t)
|
||||
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, tc.password)
|
||||
if (err == nil) != tc.valid {
|
||||
t.Fatalf("unexpected registration result: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterConflictMapsToApplicationError verifies uniqueness error translation.
|
||||
func TestRegisterConflictMapsToApplicationError(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
accounts.registerFailure = store.ErrConflict
|
||||
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password")
|
||||
if !errors.Is(err, service.ErrConflict) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterHashFailurePreservesCause checks KDF failures before persistence.
|
||||
func TestRegisterHashFailurePreservesCause(t *testing.T) {
|
||||
s, _ := authFixture(t)
|
||||
failure := errors.New("KDF unavailable")
|
||||
s.passwords = passwordFixture{failure: failure}
|
||||
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password")
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginPersistsOnlyTokenDigest checks issued entropy, owner and deadline together.
|
||||
func TestLoginPersistsOnlyTokenDigest(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
session, err := s.Login(t.Context(), "alice", "synthetic-password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session.Token == accounts.tokenHash || len(accounts.tokenHash) != 64 || session.User.ID != accounts.user.ID || !session.ExpiresAt.Equal(accounts.expiry) {
|
||||
t.Fatal("invalid issued session")
|
||||
}
|
||||
id, err := s.Authenticate(t.Context(), session.Token)
|
||||
if err != nil || id != accounts.user.ID.String() {
|
||||
t.Fatalf("session does not authenticate its owner: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginRejectsCredentials checks independent authentication rejection scenarios.
|
||||
func TestLoginRejectsCredentials(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
password string
|
||||
failure error
|
||||
expected error
|
||||
}{
|
||||
{"short password", "short", nil, service.ErrUnauthorized},
|
||||
{"wrong password", "incorrect-password", nil, service.ErrUnauthorized},
|
||||
{"missing account", "synthetic-password", store.ErrNotFound, service.ErrUnauthorized},
|
||||
{"database unavailable", "synthetic-password", context.DeadlineExceeded, context.DeadlineExceeded},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
accounts.failure = tc.failure
|
||||
_, err := s.Login(t.Context(), "alice", tc.password)
|
||||
if !errors.Is(err, tc.expected) {
|
||||
t.Fatalf("expected %v, got %v", tc.expected, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginDoesNotReturnUnpersistedSession checks failure after successful password verification.
|
||||
func TestLoginDoesNotReturnUnpersistedSession(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
accounts.saveFailure = context.DeadlineExceeded
|
||||
session, err := s.Login(t.Context(), "alice", "synthetic-password")
|
||||
if !errors.Is(err, context.DeadlineExceeded) || session.Token != "" {
|
||||
t.Fatal("unpersisted session escaped")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuthenticateRejectsUnknownToken checks malformed and correctly encoded unknown tokens.
|
||||
func TestAuthenticateRejectsUnknownToken(t *testing.T) {
|
||||
for _, token := range []string{"", "%%%", strings.Repeat("A", 43)} {
|
||||
t.Run(token, func(t *testing.T) {
|
||||
s, _ := authFixture(t)
|
||||
if _, err := s.Authenticate(t.Context(), token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuthenticatePropagatesDatabaseFailure prevents trusting a token during an outage.
|
||||
func TestAuthenticatePropagatesDatabaseFailure(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
accounts.failure = context.DeadlineExceeded
|
||||
if _, err := s.Authenticate(t.Context(), strings.Repeat("A", 43)); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLogoutRevokesIssuedToken checks that the same token cannot be reused.
|
||||
func TestLogoutRevokesIssuedToken(t *testing.T) {
|
||||
s, _ := authFixture(t)
|
||||
session, err := s.Login(t.Context(), "alice", "synthetic-password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Logout(t.Context(), session.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Authenticate(t.Context(), session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("revoked token authenticated")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewRejectsIncompleteDependencies checks constructor validation and KDF startup failure.
|
||||
func TestNewRejectsIncompleteDependencies(t *testing.T) {
|
||||
t.Run("missing accounts", func(t *testing.T) {
|
||||
if _, err := New(nil, passwordFixture{}, time.Hour); err == nil {
|
||||
t.Fatal("missing accounts accepted")
|
||||
}
|
||||
})
|
||||
t.Run("hash failure", func(t *testing.T) {
|
||||
if _, err := New(&accountFixture{}, passwordFixture{failure: context.Canceled}, time.Hour); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// ProfileCache stores immutable public account profiles; misses fall back to PostgreSQL.
|
||||
type ProfileCache interface {
|
||||
// GetProfile returns a cached profile or a miss, including on backend failure.
|
||||
GetProfile(context.Context, uuid.UUID) (dto.UserDTO, bool)
|
||||
// PutProfile stores a bounded-lifetime profile on a best-effort basis.
|
||||
PutProfile(context.Context, dto.UserDTO)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package service
|
||||
|
||||
import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
|
||||
// CursorCodec defines the pagination operations required by application services.
|
||||
type CursorCodec interface {
|
||||
// Encode signs a position for the specified resource.
|
||||
Encode(resource string, position cursor.Position) (string, error)
|
||||
|
||||
// Decode verifies a token and returns its position; empty tokens start a page sequence.
|
||||
Decode(encoded, resource string) (cursor.Position, error)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnavailable preserves the dependency failure category across service boundaries.
|
||||
ErrUnavailable = store.ErrUnavailable
|
||||
|
||||
// ErrInvalid indicates invalid operation input.
|
||||
ErrInvalid = errors.New("invalid request")
|
||||
// ErrUnauthorized indicates an unresolved current user.
|
||||
ErrUnauthorized = errors.New("unknown user identity")
|
||||
// ErrNotFound hides both absent and inaccessible resources.
|
||||
ErrNotFound = errors.New("resource not found")
|
||||
// ErrConflict indicates a duplicate username.
|
||||
ErrConflict = errors.New("username already exists")
|
||||
// ErrCapacity indicates exhausted storage capacity without eviction.
|
||||
ErrCapacity = errors.New("in-memory storage capacity reached")
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
// Package service defines the application operations consumed by HTTP controllers.
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// Service validates raw input and enforces identity and membership requirements.
|
||||
// Implementations must not expose transport-specific types or storage internals.
|
||||
type Service interface {
|
||||
// UsersCreate registers a user or reports invalid input, conflict or capacity exhaustion.
|
||||
UsersCreate(ctx context.Context, request dto.UsersCreateRequestDTO) (dto.UserDTO, error)
|
||||
|
||||
// UsersCheckIdentity verifies that an identity belongs to an existing user.
|
||||
UsersCheckIdentity(ctx context.Context, userID string) error
|
||||
|
||||
// UsersGetMe resolves the authenticated caller, rejecting malformed or unknown identifiers.
|
||||
UsersGetMe(ctx context.Context, userID string) (dto.UserDTO, error)
|
||||
|
||||
// ChatsCreate validates all members and creates one chat atomically.
|
||||
ChatsCreate(ctx context.Context, request dto.ChatsCreateRequestDTO) (dto.ChatDTO, error)
|
||||
|
||||
// ChatsGetByID hides missing and inaccessible chats behind the same not-found result.
|
||||
ChatsGetByID(ctx context.Context, userID, chatID string) (dto.ChatDTO, error)
|
||||
|
||||
// ChatsGetPage lists only chats visible to the caller, using resource-bound cursors.
|
||||
ChatsGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.ChatPageDTO, error)
|
||||
|
||||
// MessagesCreate derives the sender from the identity and appends validated text.
|
||||
MessagesCreate(ctx context.Context, request dto.MessagesCreateRequestDTO) (dto.MessageDTO, error)
|
||||
|
||||
// MessagesGetPage authorizes the caller and returns history after a verified cursor.
|
||||
MessagesGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.MessagePageDTO, error)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// parseIdentity maps malformed identity values to the authentication error.
|
||||
func parseIdentity(rawID string) (uuid.UUID, error) {
|
||||
id, err := parseID(rawID)
|
||||
if err != nil {
|
||||
return uuid.Nil, service.ErrUnauthorized
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// requireUserID resolves an existing identity without loading a user profile.
|
||||
func (s *Service) requireUserID(ctx context.Context, rawID string) (uuid.UUID, error) {
|
||||
id, err := parseIdentity(rawID)
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
exists, err := s.repo.UsersExist(ctx, []uuid.UUID{id})
|
||||
if err != nil {
|
||||
return uuid.Nil, normalizeStoreError(err)
|
||||
}
|
||||
if !exists {
|
||||
return uuid.Nil, service.ErrUnauthorized
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// requireChatMember resolves an existing caller and a chat available to that caller.
|
||||
func (s *Service) requireChatMember(ctx context.Context, userID, chatID string) (uuid.UUID, dto.ChatDTO, error) {
|
||||
caller, err := s.requireUserID(ctx, userID)
|
||||
if err != nil {
|
||||
return uuid.Nil, dto.ChatDTO{}, err
|
||||
}
|
||||
chat, err := s.findChat(ctx, chatID)
|
||||
if err != nil {
|
||||
return uuid.Nil, dto.ChatDTO{}, err
|
||||
}
|
||||
if !slices.Contains(chat.MemberIDs, caller) {
|
||||
return uuid.Nil, dto.ChatDTO{}, service.ErrNotFound
|
||||
}
|
||||
return caller, chat, nil
|
||||
}
|
||||
|
||||
// findChat parses a chat identifier and translates storage lookup errors.
|
||||
func (s *Service) findChat(ctx context.Context, rawID string) (dto.ChatDTO, error) {
|
||||
id, err := parseID(rawID)
|
||||
if err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
chat, err := s.repo.Chat(ctx, id)
|
||||
return chat, normalizeStoreError(err)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
type cacheFixture struct {
|
||||
profile dto.UserDTO
|
||||
hit bool
|
||||
writes int
|
||||
}
|
||||
|
||||
// GetProfile returns the arranged optional-cache lookup outcome.
|
||||
func (f *cacheFixture) GetProfile(context.Context, uuid.UUID) (dto.UserDTO, bool) {
|
||||
return f.profile, f.hit
|
||||
}
|
||||
|
||||
// PutProfile records successful cache population from authoritative data.
|
||||
func (f *cacheFixture) PutProfile(_ context.Context, user dto.UserDTO) {
|
||||
f.profile = user
|
||||
f.writes++
|
||||
}
|
||||
|
||||
// TestProfileCacheHitAvoidsProfileQuery verifies that the cache has a concrete role.
|
||||
func TestProfileCacheHitAvoidsProfileQuery(t *testing.T) {
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cache := &cacheFixture{profile: dto.UserDTO{ID: uuid.New()}, hit: true}
|
||||
svc, err := NewCached(&storeStub{t: t}, codec, cache)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := svc.UsersGetMe(t.Context(), cache.profile.ID.String())
|
||||
if err != nil || got.ID != cache.profile.ID {
|
||||
t.Fatalf("cache hit ignored: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProfileCacheMissPopulatesAfterDatabaseRead checks the authoritative fallback.
|
||||
func TestProfileCacheMissPopulatesAfterDatabaseRead(t *testing.T) {
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := uuid.New()
|
||||
repo := &storeStub{t: t, user: func(context.Context, uuid.UUID) (dto.UserDTO, error) {
|
||||
return dto.UserDTO{ID: id}, nil
|
||||
}}
|
||||
cache := &cacheFixture{}
|
||||
svc, err := NewCached(repo, codec, cache)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := svc.UsersGetMe(t.Context(), id.String())
|
||||
if err != nil || got.ID != id || cache.writes != 1 {
|
||||
t.Fatalf("fallback failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCachedServiceRejectsMissingDependencies checks explicit service boundaries.
|
||||
func TestCachedServiceRejectsMissingDependencies(t *testing.T) {
|
||||
t.Run("store", func(t *testing.T) {
|
||||
if _, err := NewCached(nil, nil, &cacheFixture{}); err == nil {
|
||||
t.Fatal("missing store accepted")
|
||||
}
|
||||
})
|
||||
t.Run("cache", func(t *testing.T) {
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := NewCached(&storeStub{t: t}, codec, nil); err == nil {
|
||||
t.Fatal("missing cache accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// ChatsCreate resolves the caller, validates the proposed chat and persists it atomically.
|
||||
func (s *Service) ChatsCreate(ctx context.Context, request dto.ChatsCreateRequestDTO) (dto.ChatDTO, error) {
|
||||
caller, err := s.requireUserID(ctx, request.UserID)
|
||||
if err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
chat, err := prepareChat(request, caller)
|
||||
if err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
if err := s.requireExistingMembers(ctx, chat.MemberIDs); err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
created, err := s.repo.CreateChat(ctx, chat)
|
||||
return created, normalizeStoreError(err)
|
||||
}
|
||||
|
||||
// ChatsGetByID returns a chat only to a current member, hiding its existence otherwise.
|
||||
func (s *Service) ChatsGetByID(ctx context.Context, userID, chatID string) (dto.ChatDTO, error) {
|
||||
_, chat, err := s.requireChatMember(ctx, userID, chatID)
|
||||
return chat, err
|
||||
}
|
||||
|
||||
// ChatsGetPage authorizes the caller, loads a page and prepares its continuation.
|
||||
func (s *Service) ChatsGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.ChatPageDTO, error) {
|
||||
caller, err := s.requireUserID(ctx, request.UserID)
|
||||
if err != nil {
|
||||
return dto.ChatPageDTO{}, err
|
||||
}
|
||||
page, err := s.parsePage(request, chatListResource(caller))
|
||||
if err != nil {
|
||||
return dto.ChatPageDTO{}, err
|
||||
}
|
||||
items, err := s.repo.Chats(ctx, caller, page.position, page.fetchLimit())
|
||||
if err != nil {
|
||||
return dto.ChatPageDTO{}, normalizeStoreError(err)
|
||||
}
|
||||
return s.chatPage(items, page)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// TestService_ChatsGetPage validates access and pagination before issuing a typed store query.
|
||||
func TestService_ChatsGetPage(t *testing.T) {
|
||||
t.Run("Positive: continuation uses scope, position and lookahead", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
previous := cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
records := []dto.ChatDTO{
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000001, 0).UTC()},
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000002, 0).UTC()},
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000003, 0).UTC()},
|
||||
}
|
||||
calls := 0
|
||||
repo.chats = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
calls++
|
||||
expected := dto.PositionDTO{ID: previous.ID, CreatedAt: previous.CreatedAt}
|
||||
if id != actor || position != expected || limit != 3 {
|
||||
t.Fatalf("wrong page query: id=%s, position=%v, limit=%d", id, position, limit)
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
resource := "chats:" + actor.String()
|
||||
token, err := svc.cursors.Encode(resource, previous)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), Limit: "2", Cursor: token}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || !reflect.DeepEqual(got.Items, records[:2]) || got.NextCursor == nil {
|
||||
t.Fatalf("calls=%d, page=%+v", calls, got)
|
||||
}
|
||||
position, err := svc.cursors.Decode(*got.NextCursor, resource)
|
||||
expected := cursor.Position{ID: records[1].ID, CreatedAt: records[1].CreatedAt}
|
||||
if err != nil || position != expected {
|
||||
t.Fatalf("next position=%v, want=%v, error=%v", position, expected, err)
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
t.Run("Positive: empty history uses default limit and no continuation", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
calls := 0
|
||||
repo.chats = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
calls++
|
||||
if id != actor || position != (dto.PositionDTO{}) || limit != 51 {
|
||||
t.Fatalf("wrong initial page query: id=%s, position=%v, limit=%d", id, position, limit)
|
||||
}
|
||||
return []dto.ChatDTO{}, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || got.Items == nil || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("calls=%d, page=%+v", calls, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: cursor for another resource skips page lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
svc := newStubService(t, repo)
|
||||
token, err := svc.cursors.Encode("another-resource", cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), Cursor: token}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: codec failure skips page lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
failure := errors.New("cursor unavailable")
|
||||
svc := newStubService(t, repo)
|
||||
svc.cursors = failingCursor{failure: failure}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), Cursor: "token"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: page storage fails", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
failure := errors.New("page unavailable")
|
||||
repo.chats = func(_ context.Context, _ uuid.UUID, _ dto.PositionDTO, _ int) ([]dto.ChatDTO, error) {
|
||||
return nil, failure
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips all storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
input := dto.PageRequestDTO{UserID: "invalid", ChatID: uuid.NewString()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_ChatsGetPage_InvalidLimit rejects invalid limits before reading stored pages.
|
||||
func TestService_ChatsGetPage_InvalidLimit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
limit string
|
||||
}{
|
||||
{"Negative: zero limit", "0"},
|
||||
{"Negative: negative limit", "-1"},
|
||||
{"Negative: limit above maximum", "101"},
|
||||
{"Negative: nonnumeric limit", "text"},
|
||||
{"Negative: fractional limit", "1.5"},
|
||||
{"Negative: integer overflow", "99999999999999999999999999"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), Limit: tc.limit}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestService_ChatsCreate checks membership in one batch and persists only validated chats.
|
||||
func TestService_ChatsCreate(t *testing.T) {
|
||||
t.Run("Positive: one membership query and original chat fields", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor, other := uuid.New(), uuid.New()
|
||||
var queries [][]uuid.UUID
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
queries = append(queries, slices.Clone(ids))
|
||||
return true, nil
|
||||
}
|
||||
var persisted dto.ChatDTO
|
||||
repo.createChat = func(_ context.Context, input dto.ChatDTO) (dto.ChatDTO, error) {
|
||||
persisted = input
|
||||
input.CreatedAt = time.Unix(1700000000, 0).UTC()
|
||||
return input, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: " Team 👋 ", MemberIDs: []string{actor.String(), other.String()}}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(queries, [][]uuid.UUID{{actor}, {actor, other}}) {
|
||||
t.Fatalf("existence queries=%v", queries)
|
||||
}
|
||||
if persisted.ID == uuid.Nil || persisted.Title != input.Title || !slices.Equal(persisted.MemberIDs, []uuid.UUID{actor, other}) {
|
||||
t.Fatalf("wrong persistence input: %+v", persisted)
|
||||
}
|
||||
if got.ID != persisted.ID || got.CreatedAt.IsZero() || got.Title != input.Title || !slices.Equal(got.MemberIDs, persisted.MemberIDs) {
|
||||
t.Fatalf("wrong returned chat: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown member prevents persistence", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor, missing := uuid.New(), uuid.New()
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
return !slices.Contains(ids, missing), nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String(), missing.String()}}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: membership lookup failure prevents persistence", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor, other := uuid.New(), uuid.New()
|
||||
failure := errors.New("membership unavailable")
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
if len(ids) == 1 {
|
||||
return true, nil
|
||||
}
|
||||
return false, failure
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String(), other.String()}}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown creator prevents membership and persistence calls", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
repo.usersExist = func(_ context.Context, _ []uuid.UUID) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
actor := uuid.New()
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String()}}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_ChatsCreate_InvalidInput rejects malformed chat fields before checking member existence.
|
||||
func TestService_ChatsCreate_InvalidInput(t *testing.T) {
|
||||
actor := uuid.New()
|
||||
cases := []struct {
|
||||
name string
|
||||
title string
|
||||
members []string
|
||||
}{
|
||||
{"Negative: empty member set", "Team", nil},
|
||||
{"Negative: duplicate member", "Team", []string{actor.String(), actor.String()}},
|
||||
{"Negative: caller omitted", "Team", []string{uuid.NewString()}},
|
||||
{"Negative: malformed member ID", "Team", []string{actor.String(), "invalid"}},
|
||||
{"Negative: blank title", " ", []string{actor.String()}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
calls := 0
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
calls++
|
||||
if calls != 1 || !slices.Equal(ids, []uuid.UUID{actor}) {
|
||||
t.Fatalf("unexpected membership check: %v", ids)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: tc.title, MemberIDs: tc.members}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("identity checks=%d, want=1", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_ChatsGetByID authorizes the requested chat and conceals inaccessible records.
|
||||
func TestService_ChatsGetByID(t *testing.T) {
|
||||
t.Run("Positive: member receives the complete chat", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
expected := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{actor}, CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
allowChatAccess(repo, actor, expected)
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), actor.String(), expected.ID.String())
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, expected) {
|
||||
t.Fatalf("chat=%+v, want=%+v", got, expected)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider receives no chat details", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), Title: "Private", MemberIDs: []uuid.UUID{uuid.New()}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), actor.String(), chat.ID.String())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrNotFound) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("private chat exposed: %+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed chat ID skips chat lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), actor.String(), "invalid")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), "invalid", uuid.NewString())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_ChatsGetByID_StoreErrors translates missing records and retains unexpected failures.
|
||||
func TestService_ChatsGetByID_StoreErrors(t *testing.T) {
|
||||
failure := errors.New("chat lookup unavailable")
|
||||
cases := []struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
}{
|
||||
{"Negative: absent chat", store.ErrNotFound, service.ErrNotFound},
|
||||
{"Negative: storage unavailable", failure, failure},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
repo.chat = func(_ context.Context, _ uuid.UUID) (dto.ChatDTO, error) {
|
||||
return dto.ChatDTO{}, tc.cause
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), actor.String(), uuid.NewString())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.want) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// PrepareUser validates registration fields and assigns the new user identifier.
|
||||
func PrepareUser(request dto.UsersCreateRequestDTO) (dto.UserDTO, error) {
|
||||
if !validUsername(request.Username) || !validText(request.DisplayName, maxDisplayNameRunes) {
|
||||
return dto.UserDTO{}, service.ErrInvalid
|
||||
}
|
||||
return dto.UserDTO{
|
||||
ID: uuid.New(),
|
||||
Username: request.Username,
|
||||
DisplayName: request.DisplayName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// prepareChat validates the title and member identifiers before storage access.
|
||||
func prepareChat(request dto.ChatsCreateRequestDTO, caller uuid.UUID) (dto.ChatDTO, error) {
|
||||
if !validText(request.Title, maxChatTitleRunes) {
|
||||
return dto.ChatDTO{}, service.ErrInvalid
|
||||
}
|
||||
members, err := parseMembers(request.MemberIDs, caller)
|
||||
if err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
return dto.ChatDTO{
|
||||
ID: uuid.New(),
|
||||
Title: request.Title,
|
||||
MemberIDs: members,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// prepareMessage validates text and creates a record for the authorized sender and chat.
|
||||
func prepareMessage(request dto.MessagesCreateRequestDTO, sender, chatID uuid.UUID) (dto.MessageDTO, error) {
|
||||
if !validText(request.Text, maxMessageRunes) {
|
||||
return dto.MessageDTO{}, service.ErrInvalid
|
||||
}
|
||||
return dto.MessageDTO{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: sender,
|
||||
Text: request.Text,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// normalizeStoreError maps expected storage failures to application errors.
|
||||
// Unexpected failures retain their cause for the transport's safe fallback.
|
||||
func normalizeStoreError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
return service.ErrNotFound
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
return service.ErrConflict
|
||||
case errors.Is(err, store.ErrCapacity):
|
||||
return service.ErrCapacity
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// storeStub permits only the interactions explicitly arranged by each service scenario.
|
||||
type storeStub struct {
|
||||
t *testing.T
|
||||
createUser func(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error)
|
||||
user func(ctx context.Context, id uuid.UUID) (dto.UserDTO, error)
|
||||
usersExist func(ctx context.Context, ids []uuid.UUID) (bool, error)
|
||||
createChat func(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error)
|
||||
chat func(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error)
|
||||
chats func(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error)
|
||||
createMessage func(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error)
|
||||
messages func(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error)
|
||||
}
|
||||
|
||||
// CreateUser delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.createUser == nil {
|
||||
repo.t.Fatalf("unexpected store.CreateUser call")
|
||||
return dto.UserDTO{}, nil
|
||||
}
|
||||
return repo.createUser(ctx, user)
|
||||
}
|
||||
|
||||
// User delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.user == nil {
|
||||
repo.t.Fatalf("unexpected store.User call")
|
||||
return dto.UserDTO{}, nil
|
||||
}
|
||||
return repo.user(ctx, id)
|
||||
}
|
||||
|
||||
// UsersExist delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) {
|
||||
repo.t.Helper()
|
||||
if repo.usersExist == nil {
|
||||
repo.t.Fatalf("unexpected store.UsersExist call")
|
||||
return false, nil
|
||||
}
|
||||
return repo.usersExist(ctx, ids)
|
||||
}
|
||||
|
||||
// CreateChat delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.createChat == nil {
|
||||
repo.t.Fatalf("unexpected store.CreateChat call")
|
||||
return dto.ChatDTO{}, nil
|
||||
}
|
||||
return repo.createChat(ctx, chat)
|
||||
}
|
||||
|
||||
// Chat delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.chat == nil {
|
||||
repo.t.Fatalf("unexpected store.Chat call")
|
||||
return dto.ChatDTO{}, nil
|
||||
}
|
||||
return repo.chat(ctx, id)
|
||||
}
|
||||
|
||||
// Chats delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) Chats(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.chats == nil {
|
||||
repo.t.Fatalf("unexpected store.Chats call")
|
||||
return nil, nil
|
||||
}
|
||||
return repo.chats(ctx, id, position, limit)
|
||||
}
|
||||
|
||||
// CreateMessage delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.createMessage == nil {
|
||||
repo.t.Fatalf("unexpected store.CreateMessage call")
|
||||
return dto.MessageDTO{}, nil
|
||||
}
|
||||
return repo.createMessage(ctx, message)
|
||||
}
|
||||
|
||||
// Messages delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) Messages(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.messages == nil {
|
||||
repo.t.Fatalf("unexpected store.Messages call")
|
||||
return nil, nil
|
||||
}
|
||||
return repo.messages(ctx, id, position, limit)
|
||||
}
|
||||
|
||||
// newStoreStub creates a repository that fails on every unarranged interaction.
|
||||
func newStoreStub(t *testing.T) *storeStub {
|
||||
t.Helper()
|
||||
return &storeStub{t: t}
|
||||
}
|
||||
|
||||
// newStubService composes the service with controlled storage and a real cursor codec.
|
||||
func newStubService(t *testing.T, repo *storeStub) *Service {
|
||||
t.Helper()
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc, err := New(repo, codec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// allowIdentity permits exactly the arranged actor's existence lookup, never a profile read.
|
||||
func allowIdentity(repo *storeStub, actor uuid.UUID) {
|
||||
repo.t.Helper()
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
if len(ids) != 1 || ids[0] != actor {
|
||||
repo.t.Fatalf("unexpected identity query: %v", ids)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// allowChatAccess supplies a typed chat after checking the lookup key at the service boundary.
|
||||
func allowChatAccess(repo *storeStub, actor uuid.UUID, chat dto.ChatDTO) {
|
||||
repo.t.Helper()
|
||||
allowIdentity(repo, actor)
|
||||
repo.chat = func(_ context.Context, id uuid.UUID) (dto.ChatDTO, error) {
|
||||
if id != chat.ID {
|
||||
repo.t.Fatalf("chat queried for %s, want %s", id, chat.ID)
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// parseMembers validates unique member identifiers and requires the caller to be included.
|
||||
func parseMembers(rawIDs []string, caller uuid.UUID) ([]uuid.UUID, error) {
|
||||
if len(rawIDs) == 0 || len(rawIDs) > maxChatMembers {
|
||||
return nil, service.ErrInvalid
|
||||
}
|
||||
members := make([]uuid.UUID, 0, len(rawIDs))
|
||||
seen := make(map[uuid.UUID]bool, len(rawIDs))
|
||||
for _, rawID := range rawIDs {
|
||||
id, err := parseID(rawID)
|
||||
if err != nil || seen[id] {
|
||||
return nil, service.ErrInvalid
|
||||
}
|
||||
seen[id] = true
|
||||
members = append(members, id)
|
||||
}
|
||||
if !seen[caller] {
|
||||
return nil, service.ErrInvalid
|
||||
}
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// requireExistingMembers validates the complete membership set with one storage operation.
|
||||
func (s *Service) requireExistingMembers(ctx context.Context, members []uuid.UUID) error {
|
||||
exists, err := s.repo.UsersExist(ctx, members)
|
||||
if err != nil {
|
||||
return normalizeStoreError(err)
|
||||
}
|
||||
if !exists {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// MessagesCreate authorizes the sender, validates the message and stores it atomically.
|
||||
func (s *Service) MessagesCreate(ctx context.Context, request dto.MessagesCreateRequestDTO) (dto.MessageDTO, error) {
|
||||
caller, chat, err := s.requireChatMember(ctx, request.UserID, request.ChatID)
|
||||
if err != nil {
|
||||
return dto.MessageDTO{}, err
|
||||
}
|
||||
message, err := prepareMessage(request, caller, chat.ID)
|
||||
if err != nil {
|
||||
return dto.MessageDTO{}, err
|
||||
}
|
||||
created, err := s.repo.CreateMessage(ctx, message)
|
||||
return created, normalizeStoreError(err)
|
||||
}
|
||||
|
||||
// MessagesGetPage authorizes access, loads history and prepares its continuation.
|
||||
func (s *Service) MessagesGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.MessagePageDTO, error) {
|
||||
_, chat, err := s.requireChatMember(ctx, request.UserID, request.ChatID)
|
||||
if err != nil {
|
||||
return dto.MessagePageDTO{}, err
|
||||
}
|
||||
page, err := s.parsePage(request, messageHistoryResource(chat.ID))
|
||||
if err != nil {
|
||||
return dto.MessagePageDTO{}, err
|
||||
}
|
||||
items, err := s.repo.Messages(ctx, chat.ID, page.position, page.fetchLimit())
|
||||
if err != nil {
|
||||
return dto.MessagePageDTO{}, normalizeStoreError(err)
|
||||
}
|
||||
return s.messagePage(items, page)
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// TestService_MessagesGetPage validates access and pagination before issuing a typed store query.
|
||||
func TestService_MessagesGetPage(t *testing.T) {
|
||||
t.Run("Positive: continuation uses scope, position and lookahead", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
previous := cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
records := []dto.MessageDTO{
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000001, 0).UTC()},
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000002, 0).UTC()},
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000003, 0).UTC()},
|
||||
}
|
||||
calls := 0
|
||||
repo.messages = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
calls++
|
||||
expected := dto.PositionDTO{ID: previous.ID, CreatedAt: previous.CreatedAt}
|
||||
if id != chat.ID || position != expected || limit != 3 {
|
||||
t.Fatalf("wrong page query: id=%s, position=%v, limit=%d", id, position, limit)
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
resource := "messages:" + chat.ID.String()
|
||||
token, err := svc.cursors.Encode(resource, previous)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Limit: "2", Cursor: token}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || !reflect.DeepEqual(got.Items, records[:2]) || got.NextCursor == nil {
|
||||
t.Fatalf("calls=%d, page=%+v", calls, got)
|
||||
}
|
||||
position, err := svc.cursors.Decode(*got.NextCursor, resource)
|
||||
expected := cursor.Position{ID: records[1].ID, CreatedAt: records[1].CreatedAt}
|
||||
if err != nil || position != expected {
|
||||
t.Fatalf("next position=%v, want=%v, error=%v", position, expected, err)
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
t.Run("Positive: empty history uses default limit and no continuation", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
calls := 0
|
||||
repo.messages = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
calls++
|
||||
if id != chat.ID || position != (dto.PositionDTO{}) || limit != 51 {
|
||||
t.Fatalf("wrong initial page query: id=%s, position=%v, limit=%d", id, position, limit)
|
||||
}
|
||||
return []dto.MessageDTO{}, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || got.Items == nil || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("calls=%d, page=%+v", calls, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: cursor for another resource skips page lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
svc := newStubService(t, repo)
|
||||
token, err := svc.cursors.Encode("another-resource", cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Cursor: token}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: codec failure skips page lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
failure := errors.New("cursor unavailable")
|
||||
svc := newStubService(t, repo)
|
||||
svc.cursors = failingCursor{failure: failure}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Cursor: "token"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: page storage fails", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
failure := errors.New("page unavailable")
|
||||
repo.messages = func(_ context.Context, _ uuid.UUID, _ dto.PositionDTO, _ int) ([]dto.MessageDTO, error) {
|
||||
return nil, failure
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips all storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
input := dto.PageRequestDTO{UserID: "invalid", ChatID: uuid.NewString()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider cannot read message history", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrNotFound) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_MessagesGetPage_InvalidLimit rejects invalid limits before reading stored pages.
|
||||
func TestService_MessagesGetPage_InvalidLimit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
limit string
|
||||
}{
|
||||
{"Negative: zero limit", "0"},
|
||||
{"Negative: negative limit", "-1"},
|
||||
{"Negative: limit above maximum", "101"},
|
||||
{"Negative: nonnumeric limit", "text"},
|
||||
{"Negative: fractional limit", "1.5"},
|
||||
{"Negative: integer overflow", "99999999999999999999999999"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Limit: tc.limit}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestService_MessagesCreate authorizes the sender before validating and persisting the message.
|
||||
func TestService_MessagesCreate(t *testing.T) {
|
||||
t.Run("Positive: authenticated sender and original text persisted", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
var persisted dto.MessageDTO
|
||||
repo.createMessage = func(_ context.Context, input dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
persisted = input
|
||||
input.CreatedAt = time.Unix(1700000000, 0).UTC()
|
||||
return input, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: " Original 👋 "}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if persisted.ID == uuid.Nil || persisted.SenderID != actor || persisted.ChatID != chat.ID || persisted.Text != input.Text {
|
||||
t.Fatalf("wrong persistence input: %+v", persisted)
|
||||
}
|
||||
if got.ID != persisted.ID || got.SenderID != actor || got.ChatID != chat.ID || got.Text != input.Text || got.CreatedAt.IsZero() {
|
||||
t.Fatalf("wrong acknowledgement: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider cannot persist messages", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrNotFound) || got != (dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
input := dto.MessagesCreateRequestDTO{UserID: "invalid", ChatID: uuid.NewString(), Text: "text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || got != (dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_MessagesCreate_InvalidText refuses invalid text without attempting persistence.
|
||||
func TestService_MessagesCreate_InvalidText(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
text string
|
||||
}{
|
||||
{"Negative: empty text", ""},
|
||||
{"Negative: whitespace only", " \t"},
|
||||
{"Negative: rune limit exceeded", strings.Repeat("界", 4001)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: tc.text}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || got != (dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_MessagesCreate_StoreErrors propagates persistence failures without acknowledging a record.
|
||||
func TestService_MessagesCreate_StoreErrors(t *testing.T) {
|
||||
failure := errors.New("write unavailable")
|
||||
cases := []struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
}{
|
||||
{"Negative: capacity exhausted", store.ErrCapacity, service.ErrCapacity},
|
||||
{"Negative: chat disappeared", store.ErrNotFound, service.ErrNotFound},
|
||||
{"Negative: unexpected write failure", failure, failure},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
repo.createMessage = func(_ context.Context, _ dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
return dto.MessageDTO{}, tc.cause
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.want) || got != (dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// chatPage adapts the shared page result to the chat response DTO.
|
||||
func (s *Service) chatPage(items []dto.ChatDTO, page pagination) (dto.ChatPageDTO, error) {
|
||||
items, next, err := buildPage(items, page, s.cursors, chatPosition)
|
||||
if err != nil {
|
||||
return dto.ChatPageDTO{}, err
|
||||
}
|
||||
return dto.ChatPageDTO{Items: items, NextCursor: next}, nil
|
||||
}
|
||||
|
||||
// messagePage adapts the shared page result to the message response DTO.
|
||||
func (s *Service) messagePage(items []dto.MessageDTO, page pagination) (dto.MessagePageDTO, error) {
|
||||
items, next, err := buildPage(items, page, s.cursors, messagePosition)
|
||||
if err != nil {
|
||||
return dto.MessagePageDTO{}, err
|
||||
}
|
||||
return dto.MessagePageDTO{Items: items, NextCursor: next}, nil
|
||||
}
|
||||
|
||||
// buildPage trims lookahead and signs the last returned record when more data exists.
|
||||
// The page limit must be validated before calling this helper.
|
||||
func buildPage[T any](items []T, page pagination, codec service.CursorCodec, position func(T) cursor.Position) ([]T, *string, error) {
|
||||
if len(items) <= page.limit {
|
||||
return items, nil, nil
|
||||
}
|
||||
items = items[:page.limit]
|
||||
next, err := codec.Encode(page.resource, position(items[len(items)-1]))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return items, new(next), nil
|
||||
}
|
||||
|
||||
// chatPosition extracts the stable pagination boundary from a stored chat.
|
||||
func chatPosition(chat dto.ChatDTO) cursor.Position {
|
||||
return cursor.Position{CreatedAt: chat.CreatedAt, ID: chat.ID}
|
||||
}
|
||||
|
||||
// messagePosition extracts the stable pagination boundary from a stored message.
|
||||
func messagePosition(message dto.MessageDTO) cursor.Position {
|
||||
return cursor.Position{CreatedAt: message.CreatedAt, ID: message.ID}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// TestService_messagePage checks boundaries and signs the last returned item, not lookahead.
|
||||
func TestService_messagePage(t *testing.T) {
|
||||
for _, count := range []int{0, 2, 3} {
|
||||
names := map[int]string{0: "Positive: empty page", 2: "Positive: exact limit is final", 3: "Positive: lookahead creates continuation"}
|
||||
t.Run(names[count], func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
items := make([]dto.MessageDTO, count)
|
||||
for i := range items {
|
||||
items[i] = dto.MessageDTO{ID: uuid.New(), Text: "message", CreatedAt: time.Unix(int64(i+1), 0).UTC()}
|
||||
}
|
||||
expected := items[:min(count, 2)]
|
||||
|
||||
// Act.
|
||||
page, err := svc.messagePage(items, pagination{limit: 2, resource: "messages:chat"})
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(page.Items, expected) {
|
||||
t.Fatalf("page=%v, want=%v", page.Items, expected)
|
||||
}
|
||||
if count <= 2 {
|
||||
if page.NextCursor != nil {
|
||||
t.Fatal("final page has a continuation")
|
||||
}
|
||||
return
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
t.Fatal("lookahead did not produce continuation")
|
||||
}
|
||||
decoded, err := svc.cursors.Decode(*page.NextCursor, "messages:chat")
|
||||
want := cursor.Position{ID: items[1].ID, CreatedAt: items[1].CreatedAt}
|
||||
if err != nil || decoded != want {
|
||||
t.Fatalf("cursor=%v, want=%v, error=%v", decoded, want, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPageLimit = 50
|
||||
maxPageLimit = 100
|
||||
// Fetching one extra record determines whether to issue a next cursor.
|
||||
pageLookahead = 1
|
||||
)
|
||||
|
||||
type pagination struct {
|
||||
position dto.PositionDTO
|
||||
limit int
|
||||
resource string
|
||||
}
|
||||
|
||||
// parsePage validates the page size and resource-bound cursor.
|
||||
func (s *Service) parsePage(request dto.PageRequestDTO, resource string) (pagination, error) {
|
||||
limit, err := parseLimit(request.Limit)
|
||||
if err != nil {
|
||||
return pagination{}, err
|
||||
}
|
||||
position, err := s.cursors.Decode(request.Cursor, resource)
|
||||
if errors.Is(err, cursor.ErrInvalid) {
|
||||
return pagination{}, service.ErrInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return pagination{}, err
|
||||
}
|
||||
return pagination{
|
||||
position: dto.PositionDTO{CreatedAt: position.CreatedAt, ID: position.ID},
|
||||
limit: limit,
|
||||
resource: resource,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// parseLimit parses a bounded page size or supplies the default.
|
||||
func parseLimit(raw string) (int, error) {
|
||||
if raw == "" {
|
||||
return defaultPageLimit, nil
|
||||
}
|
||||
for _, char := range raw {
|
||||
if char < '0' || char > '9' {
|
||||
return 0, service.ErrInvalid
|
||||
}
|
||||
}
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxPageLimit {
|
||||
return 0, service.ErrInvalid
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
// fetchLimit includes one lookahead record to detect a following page.
|
||||
func (page pagination) fetchLimit() int {
|
||||
return page.limit + pageLookahead
|
||||
}
|
||||
|
||||
// chatListResource scopes a cursor to one user's visible chats.
|
||||
func chatListResource(userID uuid.UUID) string {
|
||||
return "chats:" + userID.String()
|
||||
}
|
||||
|
||||
// messageHistoryResource scopes a cursor to one chat's message history.
|
||||
func messageHistoryResource(chatID uuid.UUID) string {
|
||||
return "messages:" + chatID.String()
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
type failingCursor struct {
|
||||
failure error
|
||||
}
|
||||
|
||||
// Encode injects a signing failure at the service dependency boundary.
|
||||
func (codec failingCursor) Encode(_ string, _ cursor.Position) (string, error) {
|
||||
return "", codec.failure
|
||||
}
|
||||
|
||||
// Decode injects a verification failure at the service dependency boundary.
|
||||
func (codec failingCursor) Decode(_, _ string) (cursor.Position, error) {
|
||||
return cursor.Position{}, codec.failure
|
||||
}
|
||||
|
||||
// TestService_parsePage translates invalid tokens while retaining unexpected dependency failures.
|
||||
func TestService_parsePage(t *testing.T) {
|
||||
failure := errors.New("codec unavailable")
|
||||
cases := []struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
}{
|
||||
{"Negative: invalid token", cursor.ErrInvalid, service.ErrInvalid},
|
||||
{"Negative: unavailable codec", failure, failure},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := &Service{cursors: failingCursor{failure: tc.cause}}
|
||||
input := dto.PageRequestDTO{Cursor: "supplied-token"}
|
||||
|
||||
// Act.
|
||||
page, err := svc.parsePage(input, "messages:chat")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("error=%v, want=%v", err, tc.want)
|
||||
}
|
||||
if page != (pagination{}) {
|
||||
t.Fatalf("failed cursor produced a page: %+v", page)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_messagePage_EncodeFailure returns no partial page when signing fails.
|
||||
func TestService_messagePage_EncodeFailure(t *testing.T) {
|
||||
// Arrange.
|
||||
failure := errors.New("signing unavailable")
|
||||
svc := &Service{cursors: failingCursor{failure: failure}}
|
||||
items := []dto.MessageDTO{{Text: "first"}, {Text: "lookahead"}}
|
||||
|
||||
// Act.
|
||||
page, err := svc.messagePage(items, pagination{limit: 1, resource: "messages:chat"})
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatalf("lost signing failure: %v", err)
|
||||
}
|
||||
if page.Items != nil || page.NextCursor != nil {
|
||||
t.Fatalf("partial page escaped: %+v", page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Package production implements the messenger application operations.
|
||||
package production
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// Service orchestrates operations through storage and cursor interfaces.
|
||||
type Service struct {
|
||||
repo store.Interface
|
||||
cursors service.CursorCodec
|
||||
cache service.ProfileCache
|
||||
}
|
||||
|
||||
var _ service.Service = (*Service)(nil)
|
||||
|
||||
// New creates an application service using explicitly supplied dependencies.
|
||||
func New(repo store.Interface, cursors service.CursorCodec) (*Service, error) {
|
||||
if repo == nil || cursors == nil {
|
||||
return nil, fmt.Errorf("store and cursor codec are required")
|
||||
}
|
||||
return &Service{repo: repo, cursors: cursors}, nil
|
||||
}
|
||||
|
||||
// NewCached builds the business service with optional immutable-profile caching.
|
||||
func NewCached(repo store.Interface, cursors service.CursorCodec, cache service.ProfileCache) (*Service, error) {
|
||||
instance, err := New(repo, cursors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cache == nil {
|
||||
return nil, fmt.Errorf("profile cache is required")
|
||||
}
|
||||
instance.cache = cache
|
||||
return instance, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
|
||||
)
|
||||
|
||||
// TestService_New rejects each missing dependency separately.
|
||||
func TestService_New(t *testing.T) {
|
||||
t.Run("Negative: missing store", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Act.
|
||||
svc, err := New(nil, codec)
|
||||
|
||||
// Assert.
|
||||
if err == nil || svc != nil {
|
||||
t.Fatalf("service=%v, error=%v", svc, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing codec", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
|
||||
// Act.
|
||||
svc, err := New(repo, nil)
|
||||
|
||||
// Assert.
|
||||
if err == nil || svc != nil {
|
||||
t.Fatalf("service=%v, error=%v", svc, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// UsersCreate validates registration and atomically reserves the unique username.
|
||||
func (s *Service) UsersCreate(ctx context.Context, request dto.UsersCreateRequestDTO) (dto.UserDTO, error) {
|
||||
user, err := PrepareUser(request)
|
||||
if err != nil {
|
||||
return dto.UserDTO{}, err
|
||||
}
|
||||
created, err := s.repo.CreateUser(ctx, user)
|
||||
return created, normalizeStoreError(err)
|
||||
}
|
||||
|
||||
// UsersGetMe loads the current user's profile; malformed and missing identities are unauthorized.
|
||||
func (s *Service) UsersGetMe(ctx context.Context, rawID string) (dto.UserDTO, error) {
|
||||
id, err := parseIdentity(rawID)
|
||||
if err != nil {
|
||||
return dto.UserDTO{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
if cached, ok := s.cache.GetProfile(ctx, id); ok {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
user, err := s.repo.User(ctx, id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return dto.UserDTO{}, service.ErrUnauthorized
|
||||
}
|
||||
if err == nil && s.cache != nil {
|
||||
s.cache.PutProfile(ctx, user)
|
||||
}
|
||||
return user, normalizeStoreError(err)
|
||||
}
|
||||
|
||||
// UsersCheckIdentity validates the current identity without loading its profile.
|
||||
func (s *Service) UsersCheckIdentity(ctx context.Context, rawID string) error {
|
||||
_, err := s.requireUserID(ctx, rawID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestService_UsersCreate validates registration before persistence and preserves storage failures.
|
||||
func TestService_UsersCreate(t *testing.T) {
|
||||
t.Run("Positive: validates and persists the original profile", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
expected := dto.UserDTO{Username: "alice", DisplayName: "Алиса 👋", CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
calls := 0
|
||||
repo.createUser = func(_ context.Context, input dto.UserDTO) (dto.UserDTO, error) {
|
||||
calls++
|
||||
if input.ID == uuid.Nil || input.Username != expected.Username || input.DisplayName != expected.DisplayName {
|
||||
t.Fatalf("wrong persistence input: %+v", input)
|
||||
}
|
||||
expected.ID = input.ID
|
||||
return expected, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.UsersCreateRequestDTO{Username: expected.Username, DisplayName: expected.DisplayName}
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || got != expected {
|
||||
t.Fatalf("calls=%d, got=%+v, want=%+v", calls, got, expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_UsersCreate_InvalidInput refuses malformed registrations without calling storage.
|
||||
func TestService_UsersCreate_InvalidInput(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input dto.UsersCreateRequestDTO
|
||||
}{
|
||||
{"Negative: short username", dto.UsersCreateRequestDTO{Username: "a", DisplayName: "Alice"}},
|
||||
{"Negative: uppercase username", dto.UsersCreateRequestDTO{Username: "Alice", DisplayName: "Alice"}},
|
||||
{"Negative: blank display name", dto.UsersCreateRequestDTO{Username: "alice", DisplayName: " "}},
|
||||
{"Negative: display name exceeds rune limit", dto.UsersCreateRequestDTO{Username: "alice", DisplayName: strings.Repeat("界", 101)}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange: every store method fails immediately if called.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersCreate(t.Context(), tc.input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || got != (dto.UserDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_UsersCreate_StoreErrors preserves the application meaning of persistence failures.
|
||||
func TestService_UsersCreate_StoreErrors(t *testing.T) {
|
||||
unexpected := errors.New("storage unavailable")
|
||||
cases := []struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
}{
|
||||
{"Negative: duplicate username", store.ErrConflict, service.ErrConflict},
|
||||
{"Negative: capacity exhausted", store.ErrCapacity, service.ErrCapacity},
|
||||
{"Negative: unexpected failure", unexpected, unexpected},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
repo.createUser = func(_ context.Context, _ dto.UserDTO) (dto.UserDTO, error) {
|
||||
return dto.UserDTO{}, tc.cause
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersCreate(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"})
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.want) || got != (dto.UserDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_UsersGetMe loads only the requested profile and hides unknown identities.
|
||||
func TestService_UsersGetMe(t *testing.T) {
|
||||
t.Run("Positive: returns stored profile", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
expected := dto.UserDTO{ID: uuid.New(), Username: "alice", DisplayName: "Alice", CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
calls := 0
|
||||
repo.user = func(_ context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
||||
calls++
|
||||
if id != expected.ID {
|
||||
t.Fatalf("profile queried for %s instead of %s", id, expected.ID)
|
||||
}
|
||||
return expected, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersGetMe(t.Context(), expected.ID.String())
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || got != expected {
|
||||
t.Fatalf("calls=%d, got=%+v, want=%+v", calls, got, expected)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown identity", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
repo.user = func(_ context.Context, _ uuid.UUID) (dto.UserDTO, error) {
|
||||
return dto.UserDTO{}, store.ErrNotFound
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
wantErr := service.ErrUnauthorized
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersGetMe(t.Context(), uuid.NewString())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("error=%v, want=%v", err, wantErr)
|
||||
}
|
||||
if got != (dto.UserDTO{}) {
|
||||
t.Fatalf("failed operation returned a profile: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: storage failure preserved", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
wantErr := errors.New("profile unavailable")
|
||||
repo.user = func(_ context.Context, _ uuid.UUID) (dto.UserDTO, error) {
|
||||
return dto.UserDTO{}, wantErr
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersGetMe(t.Context(), uuid.NewString())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("error=%v, want=%v", err, wantErr)
|
||||
}
|
||||
if got != (dto.UserDTO{}) {
|
||||
t.Fatalf("failed operation returned a profile: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_UsersGetMe_InvalidIdentity rejects malformed identifiers before any store call.
|
||||
func TestService_UsersGetMe_InvalidIdentity(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
}{
|
||||
{"Negative: missing header", ""},
|
||||
{"Negative: short ID", "invalid"},
|
||||
{"Negative: non-UUID characters", strings.Repeat("z", 36)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersGetMe(t.Context(), tc.raw)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || got != (dto.UserDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_UsersCheckIdentity uses the existence query and never loads a profile.
|
||||
func TestService_UsersCheckIdentity(t *testing.T) {
|
||||
t.Run("Positive: existence check without profile loading", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
id := uuid.New()
|
||||
calls := 0
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
calls++
|
||||
if !slices.Equal(ids, []uuid.UUID{id}) {
|
||||
t.Fatalf("queried IDs=%v", ids)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
err := svc.UsersCheckIdentity(t.Context(), id.String())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, nil) || calls != 1 {
|
||||
t.Fatalf("calls=%d, error=%v", calls, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: identity does not exist", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
id := uuid.New()
|
||||
calls := 0
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
calls++
|
||||
if !slices.Equal(ids, []uuid.UUID{id}) {
|
||||
t.Fatalf("queried IDs=%v", ids)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
err := svc.UsersCheckIdentity(t.Context(), id.String())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || calls != 1 {
|
||||
t.Fatalf("calls=%d, error=%v", calls, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: existence lookup fails", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
id := uuid.New()
|
||||
calls := 0
|
||||
failure := errors.New("identity unavailable")
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
calls++
|
||||
if !slices.Equal(ids, []uuid.UUID{id}) {
|
||||
t.Fatalf("queried IDs=%v", ids)
|
||||
}
|
||||
return false, failure
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
err := svc.UsersCheckIdentity(t.Context(), id.String())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || calls != 1 {
|
||||
t.Fatalf("calls=%d, error=%v", calls, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
|
||||
// Act.
|
||||
err := svc.UsersCheckIdentity(t.Context(), "invalid")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
||||
)
|
||||
|
||||
// These bounds come from the mandatory lab1 OpenAPI schema.
|
||||
const (
|
||||
minUsernameLength = 3
|
||||
maxUsernameLength = 32
|
||||
maxDisplayNameRunes = 100
|
||||
maxChatTitleRunes = 100
|
||||
maxChatMembers = 100
|
||||
maxMessageRunes = 4000
|
||||
canonicalUUIDLength = len("00000000-0000-0000-0000-000000000000")
|
||||
)
|
||||
|
||||
// validText checks that text is nonblank and within its Unicode length limit.
|
||||
func validText(value string, maxRunes int) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
|
||||
}
|
||||
|
||||
// validUsername checks the username length and permitted ASCII characters.
|
||||
func validUsername(value string) bool {
|
||||
if len(value) < minUsernameLength || len(value) > maxUsernameLength {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if (char < 'a' || char > 'z') && (char < '0' || char > '9') && char != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// parseID parses a canonical UUID or returns a validation error.
|
||||
func parseID(value string) (uuid.UUID, error) {
|
||||
if len(value) != canonicalUUIDLength {
|
||||
return uuid.Nil, service.ErrInvalid
|
||||
}
|
||||
id, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return uuid.Nil, service.ErrInvalid
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Package store defines typed persistence operations and storage errors.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnavailable means a required storage dependency cannot serve the operation.
|
||||
ErrUnavailable = errors.New("storage unavailable")
|
||||
|
||||
// ErrNotFound means a record does not exist.
|
||||
ErrNotFound = errors.New("record not found")
|
||||
|
||||
// ErrConflict means a unique constraint failed.
|
||||
ErrConflict = errors.New("record already exists")
|
||||
|
||||
// ErrCapacity means the bounded store cannot accept more data.
|
||||
ErrCapacity = errors.New("storage capacity reached")
|
||||
)
|
||||
|
||||
// Interface defines persistence operations on validated typed records.
|
||||
// Implementations own atomicity, unique constraints and storage capacity, but not
|
||||
// authorization. Callers must validate membership before accessing chat records.
|
||||
type Interface interface {
|
||||
// CreateUser atomically enforces username uniqueness and assigns CreatedAt.
|
||||
CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error)
|
||||
|
||||
// User returns a user by ID or ErrNotFound.
|
||||
User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error)
|
||||
|
||||
// UsersExist reports whether every supplied ID exists; an empty set returns true.
|
||||
UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error)
|
||||
|
||||
// CreateChat atomically stores a chat and its member indexes, assigning CreatedAt.
|
||||
CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error)
|
||||
|
||||
// Chat returns a defensive copy of the stored chat or ErrNotFound.
|
||||
Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error)
|
||||
|
||||
// Chats reads up to limit records after position from the user's chat index.
|
||||
Chats(ctx context.Context, userID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error)
|
||||
|
||||
// CreateMessage appends one message atomically and assigns its ordering timestamp.
|
||||
CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error)
|
||||
|
||||
// Messages reads up to limit records strictly after position in one chat.
|
||||
Messages(ctx context.Context, chatID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package memory
|
||||
|
||||
import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
|
||||
// Conservative logical charges, not measurements of Go allocations or RSS.
|
||||
// The budget includes record metadata and index entries; HTTP buffers are separate.
|
||||
const (
|
||||
userRecordOverheadBytes = 256
|
||||
chatRecordOverheadBytes = 256
|
||||
messageRecordOverheadBytes = 256
|
||||
chatMemberIndexBytes = 128
|
||||
usernameIndexCopies = 2
|
||||
)
|
||||
|
||||
// userCost calculates the logical storage charge for a user and its index entries.
|
||||
func userCost(user dto.UserDTO) int {
|
||||
return userRecordOverheadBytes + len(user.Username)*usernameIndexCopies + len(user.DisplayName)
|
||||
}
|
||||
|
||||
// chatCost calculates the logical storage charge for a chat and its membership index.
|
||||
func chatCost(chat dto.ChatDTO) int {
|
||||
return chatRecordOverheadBytes + len(chat.Title) + chatMemberIndexBytes*len(chat.MemberIDs)
|
||||
}
|
||||
|
||||
// messageCost calculates the logical storage charge for a message.
|
||||
func messageCost(message dto.MessageDTO) int {
|
||||
return messageRecordOverheadBytes + len(message.Text)
|
||||
}
|
||||
|
||||
// reserve checks and charges capacity while the caller holds the write lock.
|
||||
// Callers must not perform a fallible operation after reserving this budget.
|
||||
func (s *Store) reserve(bytes int) bool {
|
||||
if bytes > s.limits.MaxStateBytes-s.usedBytes {
|
||||
return false
|
||||
}
|
||||
s.usedBytes += bytes
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// copyChat copies the membership slice to keep stored chat state private.
|
||||
func copyChat(c dto.ChatDTO) dto.ChatDTO {
|
||||
c.MemberIDs = slices.Clone(c.MemberIDs)
|
||||
return c
|
||||
}
|
||||
|
||||
// CreateChat stores the chat and its member index atomically.
|
||||
func (s *Store) CreateChat(_ context.Context, c dto.ChatDTO) (dto.ChatDTO, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, id := range c.MemberIDs {
|
||||
if _, ok := s.users[id]; !ok {
|
||||
return dto.ChatDTO{}, store.ErrNotFound
|
||||
}
|
||||
}
|
||||
if len(s.chats) >= s.limits.MaxChats || !s.reserve(chatCost(c)) {
|
||||
return dto.ChatDTO{}, store.ErrCapacity
|
||||
}
|
||||
c.CreatedAt = s.timestamp()
|
||||
c = copyChat(c)
|
||||
s.chats[c.ID] = c
|
||||
for _, id := range c.MemberIDs {
|
||||
s.userChats[id] = append(s.userChats[id], c)
|
||||
}
|
||||
return copyChat(c), nil
|
||||
}
|
||||
|
||||
// Chat retrieves a defensive copy. Authorization belongs to the service.
|
||||
func (s *Store) Chat(_ context.Context, id uuid.UUID) (dto.ChatDTO, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
c, ok := s.chats[id]
|
||||
if !ok {
|
||||
return c, store.ErrNotFound
|
||||
}
|
||||
return copyChat(c), nil
|
||||
}
|
||||
|
||||
// Chats uses the per-member index and binary search, without scanning other chats.
|
||||
func (s *Store) Chats(_ context.Context, user uuid.UUID, p dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
all := s.userChats[user]
|
||||
i := sort.Search(len(all), func(i int) bool {
|
||||
return after(all[i].CreatedAt, all[i].ID, p)
|
||||
})
|
||||
end := min(len(all), i+limit)
|
||||
out := make([]dto.ChatDTO, 0, end-i)
|
||||
for _, c := range all[i:end] {
|
||||
out = append(out, copyChat(c))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestStore_CreateChat_RejectsWithoutMutation checks atomic rejection of invalid or excess chats.
|
||||
func TestStore_CreateChat_RejectsWithoutMutation(t *testing.T) {
|
||||
t.Run("Negative: chat capacity reached", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := config.Default().Memory
|
||||
cfg.MaxChats = 1
|
||||
repo := newTestStore(t, cfg)
|
||||
member := seedUser(t, repo, "alice")
|
||||
original := seedChat(t, repo, member.ID)
|
||||
input := dto.ChatDTO{ID: uuid.New(), Title: "Rejected", MemberIDs: []uuid.UUID{member.ID}}
|
||||
wantErr := store.ErrCapacity
|
||||
|
||||
previousBytes := repo.usedBytes
|
||||
|
||||
// Act.
|
||||
got, err := repo.CreateChat(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, wantErr) || got.ID != uuid.Nil {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, wantErr)
|
||||
}
|
||||
items, readErr := repo.Chats(t.Context(), member.ID, dto.PositionDTO{}, 10)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !reflect.DeepEqual(items, []dto.ChatDTO{original}) || len(repo.chats) != 1 || repo.usedBytes != previousBytes {
|
||||
t.Fatalf("rejected chat changed stored state: %v", items)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: member does not exist", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := config.Default().Memory
|
||||
cfg.MaxChats = 1
|
||||
repo := newTestStore(t, cfg)
|
||||
member := seedUser(t, repo, "alice")
|
||||
original := seedChat(t, repo, member.ID)
|
||||
input := dto.ChatDTO{ID: uuid.New(), Title: "Rejected", MemberIDs: []uuid.UUID{member.ID}}
|
||||
wantErr := store.ErrNotFound
|
||||
input.MemberIDs = append(input.MemberIDs, uuid.New())
|
||||
|
||||
previousBytes := repo.usedBytes
|
||||
|
||||
// Act.
|
||||
got, err := repo.CreateChat(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, wantErr) || got.ID != uuid.Nil {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, wantErr)
|
||||
}
|
||||
items, readErr := repo.Chats(t.Context(), member.ID, dto.PositionDTO{}, 10)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !reflect.DeepEqual(items, []dto.ChatDTO{original}) || len(repo.chats) != 1 || repo.usedBytes != previousBytes {
|
||||
t.Fatalf("rejected chat changed stored state: %v", items)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestStore_CreateChat_DefensiveCopy ensures callers cannot mutate membership through write boundaries.
|
||||
func TestStore_CreateChat_DefensiveCopy(t *testing.T) {
|
||||
t.Run("Positive: isolated input membership", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
member := seedUser(t, repo, "alice")
|
||||
input := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{member.ID}}
|
||||
_, err := repo.CreateChat(t.Context(), input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Act: a caller modifies the slice it owns after CreateChat returns.
|
||||
|
||||
input.MemberIDs[0] = uuid.New()
|
||||
|
||||
// Assert.
|
||||
stored, err := repo.Chat(t.Context(), input.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(stored.MemberIDs) != 1 || stored.MemberIDs[0] != member.ID {
|
||||
t.Fatalf("caller mutated stored membership: %+v", stored)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Positive: isolated result membership", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
member := seedUser(t, repo, "alice")
|
||||
input := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{member.ID}}
|
||||
created, err := repo.CreateChat(t.Context(), input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Act: a caller modifies the slice it owns after CreateChat returns.
|
||||
|
||||
created.MemberIDs[0] = uuid.New()
|
||||
|
||||
// Assert.
|
||||
stored, err := repo.Chat(t.Context(), input.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(stored.MemberIDs) != 1 || stored.MemberIDs[0] != member.ID {
|
||||
t.Fatalf("caller mutated stored membership: %+v", stored)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestStore_Chat_DefensiveCopy ensures a fetched detail cannot alter future reads.
|
||||
func TestStore_Chat_DefensiveCopy(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
member := seedUser(t, repo, "alice")
|
||||
original := seedChat(t, repo, member.ID)
|
||||
fetched, err := repo.Chat(t.Context(), original.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Act.
|
||||
fetched.MemberIDs[0] = uuid.New()
|
||||
|
||||
// Assert.
|
||||
stored, err := repo.Chat(t.Context(), original.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(stored, original) {
|
||||
t.Fatalf("read changed stored chat: %+v", stored)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// CreateMessage assigns ordering and publishes one complete message atomically.
|
||||
func (s *Store) CreateMessage(_ context.Context, m dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.chats[m.ChatID]; !ok {
|
||||
return dto.MessageDTO{}, store.ErrNotFound
|
||||
}
|
||||
if s.messageCount >= s.limits.MaxMessages || !s.reserve(messageCost(m)) {
|
||||
return dto.MessageDTO{}, store.ErrCapacity
|
||||
}
|
||||
m.CreatedAt = s.timestamp()
|
||||
s.messages[m.ChatID] = append(s.messages[m.ChatID], m)
|
||||
s.messageCount++
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Messages performs keyset pagination over an append-only ordered history.
|
||||
func (s *Store) Messages(_ context.Context, chat uuid.UUID, p dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
all := s.messages[chat]
|
||||
i := sort.Search(len(all), func(i int) bool {
|
||||
return after(all[i].CreatedAt, all[i].ID, p)
|
||||
})
|
||||
end := min(len(all), i+limit)
|
||||
out := make([]dto.MessageDTO, end-i)
|
||||
copy(out, all[i:end])
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestStore_CreateMessage_ByteCapacity preserves acknowledged history and accounting on rejection.
|
||||
func TestStore_CreateMessage_ByteCapacity(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := config.Default().Memory
|
||||
cfg.MaxStateBytes = 2048
|
||||
repo := newTestStore(t, cfg)
|
||||
member := seedUser(t, repo, "alice")
|
||||
chat := seedChat(t, repo, member.ID)
|
||||
original := seedMessage(t, repo, chat, "kept")
|
||||
input := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: member.ID, Text: strings.Repeat("x", 2000)}
|
||||
previousBytes := repo.usedBytes
|
||||
|
||||
// Act.
|
||||
got, err := repo.CreateMessage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, store.ErrCapacity) || got != (dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
items, readErr := repo.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 10)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !reflect.DeepEqual(items, []dto.MessageDTO{original}) || repo.messageCount != 1 || repo.usedBytes != previousBytes {
|
||||
t.Fatalf("overflow changed history or accounting: %v", items)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStore_CreateMessage_ClockRollback preserves chronological append order after a clock rollback.
|
||||
func TestStore_CreateMessage_ClockRollback(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
member := seedUser(t, repo, "alice")
|
||||
chat := seedChat(t, repo, member.ID)
|
||||
repo.lastTime = time.Now().UTC().Add(time.Hour)
|
||||
first := seedMessage(t, repo, chat, "first")
|
||||
input := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: member.ID, Text: "second"}
|
||||
|
||||
// Act.
|
||||
second, err := repo.CreateMessage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !second.CreatedAt.After(first.CreatedAt) {
|
||||
t.Fatalf("second=%s must follow first=%s", second.CreatedAt, first.CreatedAt)
|
||||
}
|
||||
page, readErr := repo.Messages(t.Context(), chat.ID, dto.PositionDTO{CreatedAt: first.CreatedAt, ID: first.ID}, 10)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !reflect.DeepEqual(page, []dto.MessageDTO{second}) {
|
||||
t.Fatalf("continuation lost the later message: %v", page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// timestamp is called under the write lock, keeping append order during clock rollback.
|
||||
func (s *Store) timestamp() time.Time {
|
||||
now := time.Now().UTC()
|
||||
if !now.After(s.lastTime) {
|
||||
now = s.lastTime.Add(time.Nanosecond)
|
||||
}
|
||||
s.lastTime = now
|
||||
return now
|
||||
}
|
||||
|
||||
// after compares a record with a keyset pagination position.
|
||||
func after(t time.Time, id uuid.UUID, p dto.PositionDTO) bool {
|
||||
return t.After(p.CreatedAt) || (t.Equal(p.CreatedAt) && bytes.Compare(id[:], p.ID[:]) > 0)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Package memory implements synchronized storage within one bounded process.
|
||||
package memory
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// Store owns all mutable state and its indexes under one lock.
|
||||
// Records are immutable once published; membership slices are copied on both
|
||||
// write and read boundaries. Its zero value is not usable; construct it with New.
|
||||
type Store struct {
|
||||
mu sync.RWMutex
|
||||
limits config.Memory
|
||||
users map[uuid.UUID]dto.UserDTO
|
||||
usernames map[string]uuid.UUID
|
||||
chats map[uuid.UUID]dto.ChatDTO
|
||||
userChats map[uuid.UUID][]dto.ChatDTO
|
||||
messages map[uuid.UUID][]dto.MessageDTO
|
||||
messageCount int
|
||||
usedBytes int
|
||||
lastTime time.Time
|
||||
}
|
||||
|
||||
var _ store.Interface = (*Store)(nil)
|
||||
|
||||
// New validates and copies capacity settings, then initializes an empty store.
|
||||
// It creates no files, goroutines or external connections.
|
||||
func New(cfg *config.Memory) (*Store, error) {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{
|
||||
limits: *cfg,
|
||||
users: make(map[uuid.UUID]dto.UserDTO),
|
||||
usernames: make(map[string]uuid.UUID),
|
||||
chats: make(map[uuid.UUID]dto.ChatDTO),
|
||||
userChats: make(map[uuid.UUID][]dto.ChatDTO),
|
||||
messages: make(map[uuid.UUID][]dto.MessageDTO),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// TestStore_New rejects missing capacity settings.
|
||||
func TestStore_New(t *testing.T) {
|
||||
// Arrange.
|
||||
var cfg *config.Memory
|
||||
|
||||
// Act.
|
||||
repo, err := New(cfg)
|
||||
|
||||
// Assert.
|
||||
if err == nil || repo != nil {
|
||||
t.Fatalf("missing configuration accepted: %v, %v", repo, err)
|
||||
}
|
||||
}
|
||||
|
||||
// newTestStore creates independent storage for one scenario.
|
||||
func newTestStore(t *testing.T, cfg *config.Memory) *Store {
|
||||
t.Helper()
|
||||
repo, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return repo
|
||||
}
|
||||
|
||||
// seedUser creates a fixture user and checks preparation errors.
|
||||
func seedUser(t *testing.T, repo *Store, username string) dto.UserDTO {
|
||||
t.Helper()
|
||||
user, err := repo.CreateUser(t.Context(), dto.UserDTO{ID: uuid.New(), Username: username})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
// seedChat creates a fixture chat for an existing member.
|
||||
func seedChat(t *testing.T, repo *Store, member uuid.UUID) dto.ChatDTO {
|
||||
t.Helper()
|
||||
chat, err := repo.CreateChat(t.Context(), dto.ChatDTO{ID: uuid.New(), Title: "Fixture", MemberIDs: []uuid.UUID{member}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return chat
|
||||
}
|
||||
|
||||
// seedMessage creates an acknowledged fixture message.
|
||||
func seedMessage(t *testing.T, repo *Store, chat dto.ChatDTO, text string) dto.MessageDTO {
|
||||
t.Helper()
|
||||
message, err := repo.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: chat.MemberIDs[0], Text: text})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return message
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// CreateUser atomically enforces uniqueness and resource limits.
|
||||
func (s *Store) CreateUser(_ context.Context, u dto.UserDTO) (dto.UserDTO, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.usernames[u.Username]; ok {
|
||||
return dto.UserDTO{}, store.ErrConflict
|
||||
}
|
||||
if len(s.users) >= s.limits.MaxUsers || !s.reserve(userCost(u)) {
|
||||
return dto.UserDTO{}, store.ErrCapacity
|
||||
}
|
||||
u.CreatedAt = s.timestamp()
|
||||
s.users[u.ID] = u
|
||||
s.usernames[u.Username] = u.ID
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// User retrieves an immutable user.
|
||||
func (s *Store) User(_ context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
u, ok := s.users[id]
|
||||
if !ok {
|
||||
return u, store.ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// UsersExist checks the complete set under one read lock without loading user records.
|
||||
// Empty sets return true, and duplicate IDs do not affect the result.
|
||||
func (s *Store) UsersExist(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
for _, id := range ids {
|
||||
if _, exists := s.users[id]; !exists {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestStore_UsersExist checks all-members semantics on an independent store per case.
|
||||
func TestStore_UsersExist(t *testing.T) {
|
||||
t.Run("Positive: existing user", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
user := seedUser(t, repo, "alice")
|
||||
ids := []uuid.UUID{user.ID}
|
||||
want := true
|
||||
|
||||
// Act.
|
||||
got, err := repo.UsersExist(t.Context(), ids)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Positive: duplicate IDs", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
user := seedUser(t, repo, "alice")
|
||||
ids := []uuid.UUID{user.ID}
|
||||
want := true
|
||||
|
||||
ids = append(ids, user.ID)
|
||||
|
||||
// Act.
|
||||
got, err := repo.UsersExist(t.Context(), ids)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Positive: empty set", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
var ids []uuid.UUID
|
||||
want := true
|
||||
|
||||
// Act.
|
||||
got, err := repo.UsersExist(t.Context(), ids)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing member", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
user := seedUser(t, repo, "alice")
|
||||
ids := []uuid.UUID{user.ID}
|
||||
want := false
|
||||
|
||||
ids = append(ids, uuid.New())
|
||||
|
||||
// Act.
|
||||
got, err := repo.UsersExist(t.Context(), ids)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestStore_CreateUser_Capacity checks that a refused user consumes no storage or username index.
|
||||
func TestStore_CreateUser_Capacity(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := config.Default().Memory
|
||||
cfg.MaxUsers = 1
|
||||
repo := newTestStore(t, cfg)
|
||||
original := seedUser(t, repo, "alice")
|
||||
rejected := dto.UserDTO{ID: uuid.New(), Username: "bob"}
|
||||
previousBytes := repo.usedBytes
|
||||
|
||||
// Act.
|
||||
got, err := repo.CreateUser(t.Context(), rejected)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, store.ErrCapacity) || got != (dto.UserDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
if len(repo.users) != 1 || repo.users[original.ID] != original || len(repo.usernames) != 1 || repo.usernames[original.Username] != original.ID || repo.usedBytes != previousBytes {
|
||||
t.Fatal("refused registration changed storage or indexes")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// CreateChat commits the chat and every member together, rolling back on any failure.
|
||||
func (s *Store) CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if err := tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES(@id,@title) RETURNING created_at`, pgx.StrictNamedArgs{"id": chat.ID, "title": chat.Title}).Scan(&chat.CreatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) SELECT @chat,id FROM unnest(@members::uuid[]) AS member(id)`, pgx.StrictNamedArgs{"chat": chat.ID, "members": chat.MemberIDs})
|
||||
return err
|
||||
})
|
||||
return chat, normalize(err)
|
||||
}
|
||||
|
||||
// Chat reads a chat and its immutable membership in one snapshot.
|
||||
func (s *Store) Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var chat dto.ChatDTO
|
||||
err := s.pool.QueryRow(ctx, `SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)
|
||||
FROM chats c WHERE c.id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
return chat, normalize(err)
|
||||
}
|
||||
|
||||
// Chats returns the requested keyset page of chats visible to a user.
|
||||
func (s *Store) Chats(ctx context.Context, userID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)
|
||||
FROM chats c JOIN chat_members m ON m.chat_id=c.id
|
||||
WHERE m.user_id=@user AND (c.created_at,c.id)>(@time,@id) ORDER BY c.created_at,c.id LIMIT @limit`, pgx.StrictNamedArgs{
|
||||
"user": userID, "time": position.CreatedAt, "id": position.ID, "limit": limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, normalize(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
chats := make([]dto.ChatDTO, 0)
|
||||
for rows.Next() {
|
||||
var chat dto.ChatDTO
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, normalize(err)
|
||||
}
|
||||
chats = append(chats, chat)
|
||||
}
|
||||
return chats, normalize(rows.Err())
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestNormalizeUnavailable classifies dependency failures while retaining their causes.
|
||||
func TestNormalizeUnavailable(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
}{
|
||||
{"deadline", context.DeadlineExceeded},
|
||||
{"closed stream", io.EOF},
|
||||
{"truncated stream", io.ErrUnexpectedEOF},
|
||||
{"network", &net.OpError{Op: "dial", Net: "tcp", Err: errors.New("refused")}},
|
||||
{"connection exception", &pgconn.PgError{Code: "08006"}},
|
||||
{"connection limit", &pgconn.PgError{Code: "53300"}},
|
||||
{"shutdown", &pgconn.PgError{Code: "57P01"}},
|
||||
{"crash", &pgconn.PgError{Code: "57P02"}},
|
||||
{"starting", &pgconn.PgError{Code: "57P03"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := normalize(fmt.Errorf("operation failed: %w", tc.err))
|
||||
if !errors.Is(err, store.ErrUnavailable) || !errors.Is(err, tc.err) {
|
||||
t.Fatalf("failure category or cause lost: %T", tc.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeUnexpected preserves programming errors instead of misclassifying them as outages.
|
||||
func TestNormalizeUnexpected(t *testing.T) {
|
||||
for _, code := range []string{"42601", "23503", "42P01"} {
|
||||
t.Run(code, func(t *testing.T) {
|
||||
err := &pgconn.PgError{Code: code}
|
||||
if normalize(err) != err {
|
||||
t.Fatal("unexpected SQL error was reclassified")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// CreateMessage serializes timestamps on the owning chat and atomically appends a message.
|
||||
func (s *Store) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if err := tx.QueryRow(ctx, `UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond')
|
||||
WHERE id=@chat RETURNING last_message_at`, pgx.StrictNamedArgs{"chat": message.ChatID}).Scan(&message.CreatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES(@id,@chat,@sender,@text,@time)`, pgx.StrictNamedArgs{
|
||||
"id": message.ID, "chat": message.ChatID, "sender": message.SenderID, "text": message.Text, "time": message.CreatedAt,
|
||||
})
|
||||
return err
|
||||
})
|
||||
return message, normalize(err)
|
||||
}
|
||||
|
||||
// Messages reads an indexed keyset page without scanning earlier history.
|
||||
func (s *Store) Messages(ctx context.Context, chatID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=@chat AND (created_at,id)>(@time,@id) ORDER BY created_at,id LIMIT @limit`, pgx.StrictNamedArgs{
|
||||
"chat": chatID, "time": position.CreatedAt, "id": position.ID, "limit": limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, normalize(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
messages := make([]dto.MessageDTO, 0)
|
||||
for rows.Next() {
|
||||
var message dto.MessageDTO
|
||||
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt); err != nil {
|
||||
return nil, normalize(err)
|
||||
}
|
||||
messages = append(messages, message)
|
||||
}
|
||||
return messages, normalize(rows.Err())
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
last_message_at timestamptz NOT NULL DEFAULT '-infinity'
|
||||
);
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY(chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user ON chat_members(user_id,chat_id);
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
FOREIGN KEY(chat_id,sender_id) REFERENCES chat_members(chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX messages_history ON messages(chat_id,created_at,id);
|
||||
CREATE TABLE sessions (
|
||||
token_hash text PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_expiry ON sessions(expires_at);
|
||||
@@ -0,0 +1,36 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// SaveSession persists an absolute expiry and a token digest in PostgreSQL.
|
||||
func (s *Store) SaveSession(ctx context.Context, hash string, userID uuid.UUID, expiry time.Time) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(ctx, `INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(@hash,@user,@expiry)`, pgx.StrictNamedArgs{
|
||||
"hash": hash, "user": userID, "expiry": expiry,
|
||||
})
|
||||
return normalize(err)
|
||||
}
|
||||
|
||||
// SessionUser rejects absent, revoked and expired sessions using database time.
|
||||
func (s *Store) SessionUser(ctx context.Context, hash string) (uuid.UUID, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var id uuid.UUID
|
||||
err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=@hash AND expires_at>clock_timestamp()`, pgx.StrictNamedArgs{"hash": hash}).Scan(&id)
|
||||
return id, normalize(err)
|
||||
}
|
||||
|
||||
// RevokeSession deletes the authoritative session before logout succeeds.
|
||||
func (s *Store) RevokeSession(ctx context.Context, hash string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash=@hash`, pgx.StrictNamedArgs{"hash": hash})
|
||||
return normalize(err)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Package postgres persists messenger records in PostgreSQL.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
//go:embed migrations/001_initial.sql
|
||||
var initialMigration string
|
||||
|
||||
const migrationLockID = 202602
|
||||
|
||||
// Options bounds database resource use.
|
||||
type Options struct {
|
||||
// URL identifies the isolated application database.
|
||||
URL string
|
||||
// MaxConnections bounds concurrent database connections.
|
||||
MaxConnections int32
|
||||
// Timeout bounds each persistence operation.
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Store owns the PostgreSQL pool; Start and Close belong to application lifecycle.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var _ store.Interface = (*Store)(nil)
|
||||
|
||||
// New validates options and builds a lazy pool without opening connections.
|
||||
func New(options Options) (*Store, error) {
|
||||
if options.URL == "" || options.MaxConnections < 1 || options.Timeout <= 0 {
|
||||
return nil, fmt.Errorf("database URL, pool bound and timeout are required")
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(options.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid database configuration")
|
||||
}
|
||||
cfg.AfterConnect = func(_ context.Context, conn *pgx.Conn) error {
|
||||
conn.TypeMap().RegisterType(&pgtype.Type{Name: "timestamptz", OID: pgtype.TimestamptzOID, Codec: &pgtype.TimestamptzCodec{ScanLocation: time.UTC}})
|
||||
return nil
|
||||
}
|
||||
cfg.MaxConns = options.MaxConnections
|
||||
cfg.ConnConfig.ConnectTimeout = options.Timeout
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{pool: pool, timeout: options.Timeout}, nil
|
||||
}
|
||||
|
||||
// Start verifies connectivity and applies versioned migrations under a transaction lock.
|
||||
func (s *Store) Start(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(@id)", pgx.StrictNamedArgs{"id": migrationLockID}); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil {
|
||||
return err
|
||||
}
|
||||
var exists bool
|
||||
if err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=1)").Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, initialMigration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES(1)")
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// Close releases owned pool resources after serving has stopped.
|
||||
func (s *Store) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
// Ping checks whether mandatory persistence can serve requests.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
return s.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
// normalize translates expected database errors without exposing SQL to higher layers.
|
||||
func normalize(err error) error {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return store.ErrNotFound
|
||||
}
|
||||
if databaseError, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
if databaseError.Code == "23505" {
|
||||
return store.ErrConflict
|
||||
}
|
||||
if strings.HasPrefix(databaseError.Code, "08") || strings.HasPrefix(databaseError.Code, "53") ||
|
||||
databaseError.Code == "57P01" || databaseError.Code == "57P02" || databaseError.Code == "57P03" {
|
||||
return fmt.Errorf("%w: %w", store.ErrUnavailable, err)
|
||||
}
|
||||
}
|
||||
var networkError net.Error
|
||||
var connectError *pgconn.ConnectError
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.As(err, &networkError) || errors.As(err, &connectError) || pgconn.SafeToRetry(err) {
|
||||
return fmt.Errorf("%w: %w", store.ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// testStore creates an isolated schema inside the explicitly configured test database.
|
||||
func testStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
url := os.Getenv("TEST_DATABASE_URL")
|
||||
if url == "" {
|
||||
t.Skip("TEST_DATABASE_URL is required for PostgreSQL integration tests")
|
||||
}
|
||||
admin, err := pgx.Connect(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
schema := "test_" + uuid.New().String()[:8]
|
||||
identifier := pgx.Identifier{schema}.Sanitize()
|
||||
if _, err := admin.Exec(t.Context(), "CREATE SCHEMA "+identifier); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
separator := "?"
|
||||
if containsQuery(url) {
|
||||
separator = "&"
|
||||
}
|
||||
s, err := New(Options{URL: url + separator + "search_path=" + schema, MaxConnections: 4, Timeout: 3 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
s.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if _, err := admin.Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := admin.Close(ctx); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if err := s.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// containsQuery identifies URL parameters without exposing credentials in test logs.
|
||||
func containsQuery(value string) bool {
|
||||
for _, char := range value {
|
||||
if char == '?' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// fixtureUser creates an independent profile for a persistence scenario.
|
||||
func fixtureUser(t *testing.T, s *Store) dto.UserDTO {
|
||||
t.Helper()
|
||||
user, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "u_" + uuid.NewString()[:8], DisplayName: "Test"}, "test-hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
// fixtureChat creates a chat containing an existing user.
|
||||
func fixtureChat(t *testing.T, s *Store, user dto.UserDTO) dto.ChatDTO {
|
||||
t.Helper()
|
||||
chat, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: uuid.New(), Title: "Test", MemberIDs: []uuid.UUID{user.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return chat
|
||||
}
|
||||
|
||||
// TestMigrationsRepeat verifies idempotent schema initialization.
|
||||
func TestMigrationsRepeat(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
if err := s.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read, err := s.User(t.Context(), user.ID)
|
||||
if err != nil || read.ID != user.ID || read.CreatedAt.Location() != time.UTC {
|
||||
t.Fatalf("migration changed data or UTC: %v", err)
|
||||
}
|
||||
if err := s.Ping(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistrationRace verifies database uniqueness under concurrent registration.
|
||||
func TestRegistrationRace(t *testing.T) {
|
||||
s := testStore(t)
|
||||
outcomes := make(chan error, 12)
|
||||
var wg sync.WaitGroup
|
||||
for range 12 {
|
||||
wg.Go(func() {
|
||||
_, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "same", DisplayName: "Test"}, "hash")
|
||||
outcomes <- err
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(outcomes)
|
||||
successes := 0
|
||||
for err := range outcomes {
|
||||
if err == nil {
|
||||
successes++
|
||||
} else if !errors.Is(err, store.ErrConflict) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if successes != 1 {
|
||||
t.Fatalf("got %d successful registrations", successes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateChatRollsBack verifies failure of membership insertion leaves no chat.
|
||||
func TestCreateChatRollsBack(t *testing.T) {
|
||||
s := testStore(t)
|
||||
id := uuid.New()
|
||||
_, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: id, Title: "Rollback", MemberIDs: []uuid.UUID{uuid.New()}})
|
||||
if err == nil {
|
||||
t.Fatal("foreign key failure absent")
|
||||
}
|
||||
if _, err := s.Chat(t.Context(), id); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("chat survived rollback: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPageUsesMembershipAndCursor verifies one compound visibility/page invariant.
|
||||
func TestChatPageUsesMembershipAndCursor(t *testing.T) {
|
||||
s := testStore(t)
|
||||
owner := fixtureUser(t, s)
|
||||
outsider := fixtureUser(t, s)
|
||||
first := fixtureChat(t, s, owner)
|
||||
second := fixtureChat(t, s, owner)
|
||||
fixtureChat(t, s, outsider)
|
||||
page, err := s.Chats(t.Context(), owner.ID, dto.PositionDTO{CreatedAt: first.CreatedAt, ID: first.ID}, 10)
|
||||
if err != nil || len(page) != 1 || page[0].ID != second.ID || len(page[0].MemberIDs) != 1 {
|
||||
t.Fatalf("invalid membership page: %+v %v", page, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessagePageOrdersConcurrentWrites verifies monotonic durable ordering and continuation.
|
||||
func TestMessagePageOrdersConcurrentWrites(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
chat := fixtureChat(t, s, user)
|
||||
var wg sync.WaitGroup
|
||||
failures := make(chan error, 20)
|
||||
for range 20 {
|
||||
wg.Go(func() {
|
||||
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "synthetic"})
|
||||
failures <- err
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(failures)
|
||||
for err := range failures {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
page, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 10)
|
||||
if err != nil || len(page) != 10 {
|
||||
t.Fatalf("first page: %d %v", len(page), err)
|
||||
}
|
||||
for index := 1; index < len(page); index++ {
|
||||
if !page[index].CreatedAt.After(page[index-1].CreatedAt) {
|
||||
t.Fatal("timestamps are not monotonic")
|
||||
}
|
||||
}
|
||||
last := page[len(page)-1]
|
||||
next, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{CreatedAt: last.CreatedAt, ID: last.ID}, 20)
|
||||
if err != nil || len(next) != 10 || !next[0].CreatedAt.After(last.CreatedAt) {
|
||||
t.Fatalf("continuation: %d %v", len(next), err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCredentialsReadsStoredHash checks credential lookup independently of public profiles.
|
||||
func TestCredentialsReadsStoredHash(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
got, hash, err := s.Credentials(t.Context(), user.Username)
|
||||
if err != nil || got.ID != user.ID || hash != "test-hash" {
|
||||
t.Fatalf("credentials mismatch: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUsersExistChecksAllIDs verifies the set membership contract.
|
||||
func TestUsersExistChecksAllIDs(t *testing.T) {
|
||||
for _, missing := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "all exist", true: "missing member"}[missing], func(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ids := []uuid.UUID{fixtureUser(t, s).ID}
|
||||
if missing {
|
||||
ids = append(ids, uuid.New())
|
||||
}
|
||||
exists, err := s.UsersExist(t.Context(), ids)
|
||||
if err != nil || exists == missing {
|
||||
t.Fatalf("exists=%v error=%v", exists, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionExpiry rejects persisted sessions whose absolute deadline has passed.
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
if err := s.SaveSession(t.Context(), "expired", user.ID, time.Now().Add(-time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.SessionUser(t.Context(), "expired"); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("expired session accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionRevocation removes a still-valid session from the source of truth.
|
||||
func TestSessionRevocation(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.RevokeSession(t.Context(), "live"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.SessionUser(t.Context(), "live"); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("revoked session accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionResolvesOwner verifies a live session's immutable identity.
|
||||
func TestSessionResolvesOwner(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := s.SessionUser(t.Context(), "live")
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatalf("invalid owner: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewRejectsInvalidOptions verifies pool construction errors without connecting.
|
||||
func TestNewRejectsInvalidOptions(t *testing.T) {
|
||||
for _, options := range []Options{{}, {URL: "://invalid", MaxConnections: 1, Timeout: time.Second}} {
|
||||
if _, err := New(options); err == nil {
|
||||
t.Fatal("invalid options accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateMessageMissingChat reports a typed missing-record error.
|
||||
func TestCreateMessageMissingChat(t *testing.T) {
|
||||
s := testStore(t)
|
||||
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: uuid.New(), SenderID: uuid.New(), Text: "test"})
|
||||
if !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessagesCanceledReturnsError verifies bounded cancellation before query execution.
|
||||
func TestMessagesCanceledReturnsError(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if _, err := s.Messages(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil {
|
||||
t.Fatal("canceled query succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatsCanceledReturnsError verifies bounded cancellation of membership pages.
|
||||
func TestChatsCanceledReturnsError(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if _, err := s.Chats(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil {
|
||||
t.Fatal("canceled query succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrationCancellationReturnsError checks startup cancellation before migration work.
|
||||
func TestMigrationCancellationReturnsError(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if err := s.Start(ctx); err == nil {
|
||||
t.Fatal("canceled migration succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrationFailureRollsBackVersion verifies a failed migration is never marked applied.
|
||||
func TestMigrationFailureRollsBackVersion(t *testing.T) {
|
||||
s := testStore(t)
|
||||
if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Start(t.Context()); err == nil {
|
||||
t.Fatal("conflicting unversioned schema accepted")
|
||||
}
|
||||
var count int
|
||||
if err := s.pool.QueryRow(t.Context(), "SELECT count(*) FROM schema_migrations").Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatal("failed migration version committed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrationRejectsBrokenVersionLedger verifies corrupt migration metadata stops startup safely.
|
||||
func TestMigrationRejectsBrokenVersionLedger(t *testing.T) {
|
||||
s := testStore(t)
|
||||
if _, err := s.pool.Exec(t.Context(), "ALTER TABLE schema_migrations RENAME COLUMN version TO broken_version"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Start(t.Context()); err == nil {
|
||||
t.Fatal("broken version ledger accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
// CreateUser inserts a profile and enforces uniqueness inside PostgreSQL.
|
||||
func (s *Store) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) {
|
||||
return s.Register(ctx, user, "")
|
||||
}
|
||||
|
||||
// Register atomically stores a profile and its password hash.
|
||||
func (s *Store) Register(ctx context.Context, user dto.UserDTO, passwordHash string) (dto.UserDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES(@id,@username,@display_name,@password_hash) RETURNING created_at`, pgx.StrictNamedArgs{
|
||||
"id": user.ID,
|
||||
"username": user.Username,
|
||||
"display_name": user.DisplayName,
|
||||
"password_hash": passwordHash,
|
||||
}).Scan(&user.CreatedAt)
|
||||
return user, normalize(err)
|
||||
}
|
||||
|
||||
// User reads a profile without credentials.
|
||||
func (s *Store) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var user dto.UserDTO
|
||||
err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at FROM users WHERE id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
return user, normalize(err)
|
||||
}
|
||||
|
||||
// Credentials reads the account needed for password verification.
|
||||
func (s *Store) Credentials(ctx context.Context, username string) (dto.UserDTO, string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var user dto.UserDTO
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=@username`, pgx.StrictNamedArgs{"username": username}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
||||
return user, hash, normalize(err)
|
||||
}
|
||||
|
||||
// UsersExist checks all distinct requested identifiers in one bounded query.
|
||||
func (s *Store) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var exists bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT NOT EXISTS (SELECT id FROM unnest(@ids::uuid[]) AS requested(id)
|
||||
WHERE NOT EXISTS (SELECT 1 FROM users WHERE users.id=requested.id))`, pgx.StrictNamedArgs{"ids": ids}).Scan(&exists)
|
||||
return exists, normalize(err)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Package strictjson decodes objects with an exact set of required, non-null fields.
|
||||
package strictjson
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"slices"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// ErrInvalid indicates invalid JSON, encoding, fields or destination field types.
|
||||
var ErrInvalid = errors.New("invalid JSON object")
|
||||
|
||||
// DecodeObject decodes one UTF-8 object with exactly the listed required fields.
|
||||
// Duplicate, unknown, missing and null fields are rejected before unmarshaling.
|
||||
// The destination must describe the supplied fields; this is not a general schema validator.
|
||||
func DecodeObject(body []byte, target any, requiredFields ...string) error {
|
||||
if !utf8.Valid(body) {
|
||||
return ErrInvalid
|
||||
}
|
||||
if err := validateObject(body, requiredFields); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(body, target); err != nil {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateObject enforces exact, unique, non-null required keys and one JSON value.
|
||||
// All lab1 request properties are required; this is not a generic schema validator.
|
||||
func validateObject(body []byte, requiredFields []string) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
token, err := decoder.Token()
|
||||
if err != nil || token != json.Delim('{') {
|
||||
return ErrInvalid
|
||||
}
|
||||
seen := make(map[string]bool, len(requiredFields))
|
||||
for decoder.More() {
|
||||
key, err := readObjectField(decoder, requiredFields, seen)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
seen[key] = true
|
||||
}
|
||||
if token, err = decoder.Token(); err != nil || token != json.Delim('}') {
|
||||
return ErrInvalid
|
||||
}
|
||||
if len(seen) != len(requiredFields) {
|
||||
return ErrInvalid
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); err != io.EOF {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readObjectField reads a known, unique, non-null JSON object field.
|
||||
func readObjectField(decoder *json.Decoder, requiredFields []string, seen map[string]bool) (string, error) {
|
||||
token, err := decoder.Token()
|
||||
if err != nil {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
key, ok := token.(string)
|
||||
if !ok || seen[key] || !slices.Contains(requiredFields, key) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
var value json.RawMessage
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package strictjson
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type input struct {
|
||||
// Name contains the only accepted field in these fixed-schema tests.
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// TestDecodeObject checks each fixed-schema rule with a fresh destination.
|
||||
func TestDecodeObject(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
wantErr error
|
||||
}{
|
||||
{"Positive: Unicode preserved", `{"name":"Алиса 👋"}`, "Алиса 👋", nil},
|
||||
{"Negative: missing field", `{}`, "", ErrInvalid},
|
||||
{"Negative: unknown field", `{"name":"alice","extra":true}`, "", ErrInvalid},
|
||||
{"Negative: duplicate field", `{"name":"alice","name":"bob"}`, "", ErrInvalid},
|
||||
{"Negative: case mismatch", `{"Name":"alice"}`, "", ErrInvalid},
|
||||
{"Negative: null field", `{"name":null}`, "", ErrInvalid},
|
||||
{"Negative: wrong value type", `{"name":12}`, "", ErrInvalid},
|
||||
{"Negative: invalid UTF-8", "{\"name\":\"\xff\"}", "", ErrInvalid},
|
||||
{"Negative: array root", `[]`, "", ErrInvalid},
|
||||
{"Negative: unclosed object", `{"name":"alice"`, "", ErrInvalid},
|
||||
{"Negative: invalid value", `{"name":}`, "", ErrInvalid},
|
||||
{"Negative: invalid key", `{name:"alice"}`, "", ErrInvalid},
|
||||
{"Negative: trailing value", `{"name":"alice"} {}`, "", ErrInvalid},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
var destination input
|
||||
|
||||
// Act.
|
||||
err := DecodeObject([]byte(tc.body), &destination, "name")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.wantErr) {
|
||||
t.Fatalf("error=%v, want=%v", err, tc.wantErr)
|
||||
}
|
||||
if destination.Name != tc.want {
|
||||
t.Fatalf("decoded name=%q, want=%q", destination.Name, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package valkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission"
|
||||
)
|
||||
|
||||
const (
|
||||
admissionWindow = time.Second
|
||||
admissionLease = 30 * time.Second
|
||||
releaseTimeout = time.Second
|
||||
)
|
||||
|
||||
// Budget defines a rate window and concurrent execution capacity.
|
||||
type Budget struct {
|
||||
// Rate is the maximum attempts per one-second window.
|
||||
Rate int
|
||||
// Slots is the maximum requests executing concurrently.
|
||||
Slots int
|
||||
}
|
||||
|
||||
// Limits separates global, route-group and user budgets.
|
||||
type Limits struct {
|
||||
// Global covers every business request before authentication.
|
||||
Global Budget
|
||||
// Groups covers auth, read and write independently.
|
||||
Groups map[string]Budget
|
||||
// User covers all authenticated requests made by one account.
|
||||
User Budget
|
||||
// UserGroups limits each authenticated account within a route group.
|
||||
UserGroups map[string]Budget
|
||||
}
|
||||
|
||||
// Limiter applies atomic local-shard decisions; global reservations precede user reservations.
|
||||
type Limiter struct {
|
||||
client *Client
|
||||
limits Limits
|
||||
}
|
||||
|
||||
// NewLimiter validates independent rate and concurrency budgets.
|
||||
func NewLimiter(client *Client, limits Limits) (*Limiter, error) {
|
||||
if client == nil || limits.Global.Rate < 1 || limits.Global.Slots < 1 || limits.User.Rate < 1 || limits.User.Slots < 1 {
|
||||
return nil, fmt.Errorf("client and positive budgets are required")
|
||||
}
|
||||
for _, group := range []string{"auth", "read", "write"} {
|
||||
global := limits.Groups[group]
|
||||
user := limits.UserGroups[group]
|
||||
if global.Rate < 1 || global.Slots < 1 || user.Rate < 1 || user.Slots < 1 {
|
||||
return nil, fmt.Errorf("positive budgets for every group are required")
|
||||
}
|
||||
}
|
||||
groups := make(map[string]Budget, len(limits.Groups))
|
||||
userGroups := make(map[string]Budget, len(limits.UserGroups))
|
||||
for key, value := range limits.Groups {
|
||||
groups[key] = value
|
||||
}
|
||||
for key, value := range limits.UserGroups {
|
||||
userGroups[key] = value
|
||||
}
|
||||
limits.Groups = groups
|
||||
limits.UserGroups = userGroups
|
||||
return &Limiter{client: client, limits: limits}, nil
|
||||
}
|
||||
|
||||
// Enter atomically reserves two rate and slot budgets on one shard.
|
||||
// Global admission precedes authentication; user admission follows verified identity.
|
||||
func (l *Limiter) Enter(ctx context.Context, group, user string) (func(), error) {
|
||||
groupBudget, ok := l.limits.Groups[group]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown admission group")
|
||||
}
|
||||
totalBudget := l.limits.Global
|
||||
node := l.client.coordinator
|
||||
prefix := "admission:global"
|
||||
if user != "" {
|
||||
prefix = "admission:user:" + user
|
||||
node = l.client.nodes[l.client.ring.Owner(prefix)]
|
||||
totalBudget = l.limits.User
|
||||
groupBudget = l.limits.UserGroups[group]
|
||||
}
|
||||
keys := []string{prefix + ":rate", prefix + ":slots", prefix + ":" + group + ":rate", prefix + ":" + group + ":slots"}
|
||||
token := uuid.NewString()
|
||||
ctx, cancel := context.WithTimeout(ctx, l.client.timeout)
|
||||
defer cancel()
|
||||
result, err := node.Eval(ctx, reserveScript, keys, token, admissionWindow.Milliseconds(), admissionLease.Milliseconds(), totalBudget.Rate, totalBudget.Slots, groupBudget.Rate, groupBudget.Slots).Int()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result == 1 {
|
||||
return nil, admission.ErrRate
|
||||
}
|
||||
if result == 2 {
|
||||
return nil, admission.ErrSlots
|
||||
}
|
||||
return func() {
|
||||
releaseCtx, releaseCancel := context.WithTimeout(context.Background(), releaseTimeout)
|
||||
defer releaseCancel()
|
||||
// Failed release is bounded by the lease; tokens are never reused.
|
||||
_ = node.Eval(releaseCtx, releaseScript, []string{keys[1], keys[3]}, token).Err()
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Redis TIME and one Lua operation make check-and-reserve indivisible within a shard.
|
||||
const reserveScript = `
|
||||
local clock = redis.call('TIME')
|
||||
local now = clock[1]*1000 + math.floor(clock[2]/1000)
|
||||
for i=1,3,2 do
|
||||
redis.call('ZREMRANGEBYSCORE',KEYS[i+1],'-inf',now)
|
||||
local rate = tonumber(redis.call('GET',KEYS[i]) or '0')
|
||||
local limitIndex = i==1 and 4 or 6
|
||||
if rate >= tonumber(ARGV[limitIndex]) then return 1 end
|
||||
if redis.call('ZCARD',KEYS[i+1]) >= tonumber(ARGV[limitIndex+1]) then return 2 end
|
||||
end
|
||||
for i=1,3,2 do
|
||||
local count = redis.call('INCR',KEYS[i])
|
||||
if count==1 then redis.call('PEXPIRE',KEYS[i],ARGV[2]) end
|
||||
redis.call('ZADD',KEYS[i+1],now+tonumber(ARGV[3]),ARGV[1])
|
||||
redis.call('PEXPIRE',KEYS[i+1],ARGV[3])
|
||||
end
|
||||
return 0
|
||||
`
|
||||
|
||||
const releaseScript = `
|
||||
redis.call('ZREM',KEYS[1],ARGV[1])
|
||||
redis.call('ZREM',KEYS[2],ARGV[1])
|
||||
return 0
|
||||
`
|
||||
@@ -0,0 +1,42 @@
|
||||
package valkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
)
|
||||
|
||||
const profileTTL = 5 * time.Minute
|
||||
|
||||
// GetProfile reads an immutable profile; corrupt values and outages are cache misses.
|
||||
func (c *Client) GetProfile(ctx context.Context, id uuid.UUID) (dto.UserDTO, bool) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
key := "profile:" + id.String()
|
||||
value, err := c.nodes[c.ring.Owner(key)].Get(ctx, key).Bytes()
|
||||
if err != nil {
|
||||
return dto.UserDTO{}, false
|
||||
}
|
||||
var user dto.UserDTO
|
||||
if json.Unmarshal(value, &user) != nil || user.ID != id {
|
||||
return dto.UserDTO{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
// PutProfile populates the immutable profile cache with a bounded TTL.
|
||||
func (c *Client) PutProfile(ctx context.Context, user dto.UserDTO) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
value, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
key := "profile:" + user.ID.String()
|
||||
// Cache writes are best effort; PostgreSQL remains the source of truth.
|
||||
_ = c.nodes[c.ring.Owner(key)].Set(ctx, key, value, profileTTL).Err()
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Package valkey implements sharded cache and admission infrastructure.
|
||||
package valkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/hashring"
|
||||
)
|
||||
|
||||
const virtualNodes = 256
|
||||
|
||||
// Options bounds each independent Valkey connection pool.
|
||||
type Options struct {
|
||||
// Nodes maps stable shard identities to network addresses.
|
||||
Nodes map[string]string
|
||||
// Coordinator identifies the stable global admission shard.
|
||||
Coordinator string
|
||||
// Timeout bounds operations and pool acquisition.
|
||||
Timeout time.Duration
|
||||
// PoolSize bounds connections to each shard.
|
||||
PoolSize int
|
||||
}
|
||||
|
||||
// Client owns a fixed topology; callers must drain before changing it.
|
||||
type Client struct {
|
||||
nodes map[string]*redis.Client
|
||||
ring *hashring.Ring
|
||||
coordinator *redis.Client
|
||||
timeout time.Duration
|
||||
topology string
|
||||
}
|
||||
|
||||
// New prepares lazy clients without opening network connections.
|
||||
func New(options Options) (*Client, error) {
|
||||
if len(options.Nodes) < 1 || options.PoolSize < 1 || options.Timeout <= 0 {
|
||||
return nil, fmt.Errorf("valkey nodes, pool bound and timeout are required")
|
||||
}
|
||||
ids := make([]string, 0, len(options.Nodes))
|
||||
for id, address := range options.Nodes {
|
||||
if address == "" {
|
||||
return nil, fmt.Errorf("valkey address is required")
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
ring, err := hashring.New(ids, virtualNodes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := options.Nodes[options.Coordinator]; !ok {
|
||||
return nil, fmt.Errorf("coordinator must identify a configured node")
|
||||
}
|
||||
sort.Strings(ids)
|
||||
topologyHash := sha256.Sum256([]byte(strings.Join(ids, ",")))
|
||||
client := &Client{nodes: make(map[string]*redis.Client), ring: ring, timeout: options.Timeout}
|
||||
for id, address := range options.Nodes {
|
||||
client.nodes[id] = redis.NewClient(&redis.Options{
|
||||
Addr: address,
|
||||
PoolSize: options.PoolSize,
|
||||
MaxActiveConns: options.PoolSize,
|
||||
PoolTimeout: options.Timeout,
|
||||
DialTimeout: options.Timeout,
|
||||
ReadTimeout: options.Timeout,
|
||||
WriteTimeout: options.Timeout,
|
||||
ContextTimeoutEnabled: true,
|
||||
MaxRetries: -1,
|
||||
})
|
||||
}
|
||||
client.topology = hex.EncodeToString(topologyHash[:])
|
||||
client.coordinator = client.nodes[options.Coordinator]
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Ping checks every shard required for safe admission.
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
for _, node := range c.nodes {
|
||||
if err := node.Ping(ctx).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
stored, err := c.coordinator.Eval(ctx, topologyScript, []string{"admission:topology"}, c.topology).Text()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if stored != c.topology {
|
||||
return fmt.Errorf("valkey topology differs: stop admission and drain before changing the ring")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const topologyScript = `
|
||||
redis.call('SET',KEYS[1],ARGV[1],'NX')
|
||||
return redis.call('GET',KEYS[1])
|
||||
`
|
||||
|
||||
// Close releases every connection pool owned by the client.
|
||||
func (c *Client) Close() error {
|
||||
var result error
|
||||
for _, node := range c.nodes {
|
||||
result = errors.Join(result, node.Close())
|
||||
}
|
||||
return result
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user