forked from mtusi2026/mtusi2026lab3
Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
"highload/internal/repository"
|
||||
)
|
||||
|
||||
type logoutObservationKey struct{}
|
||||
type logoutObservation struct {
|
||||
Group int `json:"clients"`
|
||||
Round int `json:"round"`
|
||||
PauseMS int `json:"pause_ms"`
|
||||
ElapsedMS float64 `json:"elapsed_ms"`
|
||||
WaitMS float64 `json:"waitaof_ms"`
|
||||
DelID int64 `json:"del_connection_id"`
|
||||
WaitID int64 `json:"wait_connection_id"`
|
||||
Local *int64 `json:"local_fsynced"`
|
||||
Replicas *int64 `json:"replicas_fsynced"`
|
||||
Kind string `json:"kind"`
|
||||
CommandError string `json:"command_error,omitempty"`
|
||||
RepositoryError string `json:"repository_error,omitempty"`
|
||||
}
|
||||
type logoutAOFObservation struct{}
|
||||
|
||||
func (h logoutAOFObservation) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (h logoutAOFObservation) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (h logoutAOFObservation) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
started := time.Now()
|
||||
err := next(ctx, cmd)
|
||||
row, _ := ctx.Value(logoutObservationKey{}).(*logoutObservation)
|
||||
if row == nil {
|
||||
return err
|
||||
}
|
||||
name := cmd.Name()
|
||||
if name != "del" && name != "waitaof" {
|
||||
return err
|
||||
}
|
||||
if name == "waitaof" {
|
||||
row.WaitMS = float64(time.Since(started)) / float64(time.Millisecond)
|
||||
if err != nil {
|
||||
row.CommandError = err.Error()
|
||||
row.Kind = "command_error"
|
||||
} else {
|
||||
if value, ok := cmd.(*redisclient.Cmd); ok {
|
||||
if reply, ok := value.Val().([]any); ok && len(reply) == 2 {
|
||||
local, lok := reply[0].(int64)
|
||||
replicas, rok := reply[1].(int64)
|
||||
if lok && rok {
|
||||
row.Local = &local
|
||||
row.Replicas = &replicas
|
||||
row.Kind = "acknowledged"
|
||||
if local != 1 {
|
||||
row.Kind = "unacknowledged"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if row.Local == nil {
|
||||
row.Kind = "unexpected_reply"
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
// next is bound to this Conn's processing path. The observation adds a
|
||||
// read-only CLIENT ID on that same path; it never gets a second pool slot.
|
||||
id := redisclient.NewIntCmd(ctx, "CLIENT", "ID")
|
||||
if e := next(ctx, id); e == nil {
|
||||
if name == "del" {
|
||||
row.DelID = id.Val()
|
||||
} else {
|
||||
row.WaitID = id.Val()
|
||||
}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisLogoutPersistenceDiagnostic(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
f.client.AddHook(logoutAOFObservation{})
|
||||
before := f.client.PoolStats()
|
||||
rows := []logoutObservation{}
|
||||
var mu sync.Mutex
|
||||
stop := make(chan struct{})
|
||||
sampled := make(chan struct{})
|
||||
poolSamples := []map[string]any{}
|
||||
go func() {
|
||||
defer close(sampled)
|
||||
ticker := time.NewTicker(50 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
poolSamples = append(poolSamples, map[string]any{"at": time.Now().UTC().Format(time.RFC3339Nano), "stats": f.client.PoolStats()})
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
close(stop)
|
||||
<-sampled
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for f.client.PoolStats().TotalConns != f.client.PoolStats().IdleConns && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
after := f.client.PoolStats()
|
||||
if after.TotalConns != after.IdleConns || after.PendingRequests != 0 {
|
||||
t.Error("logout left acquired/pending pool connections")
|
||||
}
|
||||
report := map[string]any{"pool_before": before, "pool_after": after, "pool_samples": poolSamples, "samples": rows, "production_options": map[string]any{"read_timeout_ms": f.client.Options().ReadTimeout.Milliseconds(), "pool_size": f.client.Options().PoolSize, "pool_timeout_ms": f.client.Options().PoolTimeout.Milliseconds()}, "instrumentation": "read-only CLIENT ID after DEL and WAITAOF, on the pinned processing path"}
|
||||
if directory := os.Getenv("AUTH_TEST_DIAGNOSTICS_DIR"); directory != "" {
|
||||
_ = os.MkdirAll(directory, 0700)
|
||||
data, _ := json.MarshalIndent(report, "", " ")
|
||||
if os.WriteFile(filepath.Join(directory, "redis-logout.json"), data, 0600) != nil {
|
||||
t.Error("cannot save Redis diagnostics")
|
||||
}
|
||||
}
|
||||
t.Logf("logout samples=%d pool_wait_count=%d wait_ns=%d pool_timeouts=%d final_busy=%d", len(rows), after.WaitCount-before.WaitCount, after.WaitDurationNs-before.WaitDurationNs, after.Timeouts-before.Timeouts, after.TotalConns-after.IdleConns)
|
||||
}()
|
||||
run := func(clients, round, pause int) {
|
||||
var workers sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for range clients {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
// Two sessions for one synthetic identity: revoking one must leave the
|
||||
// other valid, even while other workers revoke their own sessions.
|
||||
first, other := f.trackSafe(uuid.NewString()), f.trackSafe(uuid.NewString())
|
||||
user := uuid.NewString()
|
||||
if _, err := f.repo.Create(f.ctx, first[:], user, time.Minute); err != nil {
|
||||
t.Error("create logout fixture failed")
|
||||
return
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, other[:], user, time.Minute); err != nil {
|
||||
t.Error("create independent fixture failed")
|
||||
return
|
||||
}
|
||||
<-start
|
||||
time.Sleep(time.Duration(pause) * time.Millisecond)
|
||||
row := logoutObservation{Group: clients, Round: round, PauseMS: pause}
|
||||
ctx := context.WithValue(f.ctx, logoutObservationKey{}, &row)
|
||||
began := time.Now()
|
||||
_, err := f.repo.RevokeSession(ctx, first[:])
|
||||
row.ElapsedMS = float64(time.Since(began)) / float64(time.Millisecond)
|
||||
if err != nil {
|
||||
row.RepositoryError = err.Error()
|
||||
t.Errorf("logout clients=%d kind=%s category=%v", clients, row.Kind, err)
|
||||
}
|
||||
if row.Kind == "unacknowledged" && !errors.Is(err, repository.ErrServiceUnavailable) {
|
||||
t.Error("unacknowledged local fsync must preserve unavailable category")
|
||||
}
|
||||
if row.DelID == 0 || row.DelID != row.WaitID {
|
||||
t.Error("DEL/WAITAOF connection identity not preserved")
|
||||
}
|
||||
if _, err = f.repo.GetSessionByTokenHash(f.ctx, other[:]); err != nil {
|
||||
t.Error("concurrent logout affected independent session")
|
||||
}
|
||||
if _, err = f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repository.ErrNotFound) {
|
||||
t.Error("revoked session still available")
|
||||
}
|
||||
mu.Lock()
|
||||
rows = append(rows, row)
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
}
|
||||
for i, pause := range []int{0, 137, 359, 613, 887, 1109} {
|
||||
run(1, i+1, pause)
|
||||
}
|
||||
for _, clients := range []int{5, 10} {
|
||||
for round := 1; round <= 3; round++ {
|
||||
run(clients, round, 137*round)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// track modifies fixture cleanup bookkeeping; concurrent probes synchronize it.
|
||||
var diagnosticTrackMu sync.Mutex
|
||||
|
||||
func (f *redisFixture) trackSafe(token string) [32]byte {
|
||||
diagnosticTrackMu.Lock()
|
||||
defer diagnosticTrackMu.Unlock()
|
||||
return f.track(token)
|
||||
}
|
||||
Reference in New Issue
Block a user