forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
package valkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/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/mtusi2026lab6/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/mtusi2026lab6/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
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package valkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/admission"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user