package valkey import ( "context" "errors" "os" "sync" "sync/atomic" "testing" "time" "github.com/google/uuid" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/admission" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" ) // testClient connects only to explicitly configured disposable Valkey shards. func testClient(t *testing.T) *Client { t.Helper() address := os.Getenv("TEST_VALKEY_ADDRESS") if address == "" { t.Skip("TEST_VALKEY_ADDRESS is required for Valkey integration tests") } client, err := New(Options{Nodes: map[string]string{"test": address}, Coordinator: "test", PoolSize: 16, Timeout: time.Second}) if err != nil { t.Fatal(err) } t.Cleanup(func() { if err := client.Close(); err != nil { t.Error(err) } }) if err := client.Ping(t.Context()); err != nil { t.Fatal(err) } return client } // testLimits builds independent small budgets for admission scenarios. func testLimits() Limits { return Limits{ Global: Budget{Rate: 10000, Slots: 100}, User: Budget{Rate: 1000, Slots: 3}, Groups: map[string]Budget{ "auth": {Rate: 100, Slots: 4}, "read": {Rate: 1000, Slots: 50}, "write": {Rate: 1000, Slots: 50}, }, UserGroups: map[string]Budget{ "auth": {Rate: 10, Slots: 1}, "read": {Rate: 100, Slots: 2}, "write": {Rate: 100, Slots: 2}, }, } } // TestPerUserSlotsAreAtomic verifies concurrent reservations cannot exceed the group budget. func TestPerUserSlotsAreAtomic(t *testing.T) { client := testClient(t) limiter, err := NewLimiter(client, testLimits()) if err != nil { t.Fatal(err) } user := uuid.NewString() var accepted atomic.Int32 releases := make(chan func(), 30) failures := make(chan error, 30) var wg sync.WaitGroup for range 30 { wg.Go(func() { release, err := limiter.Enter(t.Context(), "read", user) if err == nil { accepted.Add(1) releases <- release } else if !errors.Is(err, admission.ErrSlots) { failures <- err } }) } wg.Wait() close(releases) close(failures) for release := range releases { release() } for err := range failures { t.Error(err) } if accepted.Load() != 2 { t.Fatalf("accepted %d, want exactly two", accepted.Load()) } } // TestUserGroupsHaveSeparateSlots verifies read saturation does not consume write-group capacity. func TestUserGroupsHaveSeparateSlots(t *testing.T) { client := testClient(t) limiter, err := NewLimiter(client, testLimits()) if err != nil { t.Fatal(err) } user := uuid.NewString() for range 2 { release, err := limiter.Enter(t.Context(), "read", user) if err != nil { t.Fatal(err) } t.Cleanup(release) } release, err := limiter.Enter(t.Context(), "write", user) if err != nil { t.Fatal(err) } release() } // TestUserRateSurvivesSlotRelease checks that release returns concurrency but not rate tokens. func TestUserRateSurvivesSlotRelease(t *testing.T) { client := testClient(t) limits := testLimits() limits.User.Rate = 1 limiter, err := NewLimiter(client, limits) if err != nil { t.Fatal(err) } user := uuid.NewString() release, err := limiter.Enter(t.Context(), "read", user) if err != nil { t.Fatal(err) } release() if _, err := limiter.Enter(t.Context(), "read", user); !errors.Is(err, admission.ErrRate) { t.Fatalf("rate budget reset after release: %v", err) } } // TestAdmissionRejectsUnavailableBackend verifies fail-closed behavior without network fallback. func TestAdmissionRejectsUnavailableBackend(t *testing.T) { client := testClient(t) limiter, err := NewLimiter(client, testLimits()) if err != nil { t.Fatal(err) } ctx, cancel := context.WithCancel(t.Context()) cancel() if _, err := limiter.Enter(ctx, "read", ""); err == nil { t.Fatal("canceled backend operation admitted request") } } // TestGlobalAdmissionReleasesSlots verifies the coordinator path and release semantics. func TestGlobalAdmissionReleasesSlots(t *testing.T) { client := testClient(t) limiter, err := NewLimiter(client, testLimits()) if err != nil { t.Fatal(err) } release, err := limiter.Enter(t.Context(), "read", "") if err != nil { t.Fatal(err) } release() } // TestProfileRoundTrip checks storage and ownership of immutable cached profiles. func TestProfileRoundTrip(t *testing.T) { client := testClient(t) user := dto.UserDTO{ID: uuid.New(), Username: "synthetic", DisplayName: "Test", CreatedAt: time.Now().UTC()} client.PutProfile(t.Context(), user) got, ok := client.GetProfile(t.Context(), user.ID) if !ok || got.ID != user.ID || got.Username != user.Username { t.Fatal("profile cache did not preserve account") } } // TestProfileMissHandlesCorruption verifies corrupt cache entries cannot impersonate another account. func TestProfileMissHandlesCorruption(t *testing.T) { client := testClient(t) id := uuid.New() key := "profile:" + id.String() if err := client.nodes[client.ring.Owner(key)].Set(t.Context(), key, `{"ID":"00000000-0000-0000-0000-000000000000"}`, time.Minute).Err(); err != nil { t.Fatal(err) } if _, ok := client.GetProfile(t.Context(), id); ok { t.Fatal("corrupt profile accepted") } } // TestProfileBackendFailureIsMiss checks optional-cache fallback semantics. func TestProfileBackendFailureIsMiss(t *testing.T) { client := testClient(t) ctx, cancel := context.WithCancel(t.Context()) cancel() if _, ok := client.GetProfile(ctx, uuid.New()); ok { t.Fatal("failed cache read treated as hit") } client.PutProfile(ctx, dto.UserDTO{ID: uuid.New()}) if err := client.Ping(ctx); err == nil { t.Fatal("canceled readiness succeeded") } } // TestClientRejectsInvalidConfiguration covers configuration boundaries without opening sockets. func TestClientRejectsInvalidConfiguration(t *testing.T) { cases := []Options{ {}, {Nodes: map[string]string{"a": ""}, Coordinator: "a", PoolSize: 1, Timeout: time.Second}, {Nodes: map[string]string{"": "localhost:6379"}, Coordinator: "", PoolSize: 1, Timeout: time.Second}, {Nodes: map[string]string{"a": "localhost:6379"}, Coordinator: "b", PoolSize: 1, Timeout: time.Second}, } for index, options := range cases { t.Run(string(rune('a'+index)), func(t *testing.T) { if _, err := New(options); err == nil { t.Fatal("invalid client options accepted") } }) } } // TestLimiterRejectsInvalidConfiguration verifies policy completeness. func TestLimiterRejectsInvalidConfiguration(t *testing.T) { if _, err := NewLimiter(nil, testLimits()); err == nil { t.Fatal("nil client accepted") } client := testClient(t) limits := testLimits() delete(limits.Groups, "auth") if _, err := NewLimiter(client, limits); err == nil { t.Fatal("missing group accepted") } limiter, err := NewLimiter(client, testLimits()) if err != nil { t.Fatal(err) } if _, err := limiter.Enter(t.Context(), "unknown", ""); err == nil { t.Fatal("unknown group accepted") } } // TestTopologyMismatchFailsClosed prevents replicas from silently splitting user budgets. func TestTopologyMismatchFailsClosed(t *testing.T) { client := testClient(t) client.topology = "different-ring" if err := client.Ping(t.Context()); err == nil { t.Fatal("incompatible topology accepted") } }