github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/store/redis/ephemeral_test.go (about) 1 package redis 2 3 import ( 4 "context" 5 "testing" 6 "time" 7 8 "github.com/alicebob/miniredis/v2" 9 "github.com/go-redis/redis/v8" 10 "github.com/projecteru2/core/utils" 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func (s *RediaronTestSuite) TestEphemeralDeregister() { 15 ctx := context.Background() 16 path := "/ident" 17 heartbeat := time.Second 18 expiry, stop, err := s.rediaron.StartEphemeral(ctx, path, heartbeat) 19 s.NoError(err) 20 s.NotNil(stop) 21 s.NotNil(expiry) 22 23 v, err := s.rediaron.GetOne(ctx, path) 24 s.NoError(err) 25 s.Equal(ephemeralValue, v) 26 27 stop() 28 v, err = s.rediaron.GetOne(ctx, path) 29 s.Error(err) 30 s.Empty(v) 31 } 32 33 func (s *RediaronTestSuite) TestEphemeral() { 34 ctx := context.Background() 35 path := "/ident" 36 heartbeat := time.Second 37 expiry, stop, err := s.rediaron.StartEphemeral(ctx, path, heartbeat) 38 s.NoError(err) 39 s.NotNil(stop) 40 s.NotNil(expiry) 41 42 v, err := s.rediaron.GetOne(ctx, path) 43 s.NoError(err) 44 s.Equal(ephemeralValue, v) 45 46 // Makes sure that the ephemeral keeps alived. 47 time.Sleep(heartbeat * 2) 48 v, err = s.rediaron.GetOne(ctx, path) 49 s.NoError(err) 50 s.Equal(ephemeralValue, v) 51 52 select { 53 case <-expiry: 54 s.FailNow("unexpected expired") 55 default: 56 } 57 58 // Stop and waiting for expiry. 59 stop() 60 time.Sleep(heartbeat * 2) 61 // Ephemeral kv has been removed. 62 v, err = s.rediaron.GetOne(ctx, path) 63 s.Error(err) // no such path 64 s.Empty(v) 65 66 select { 67 case <-expiry: 68 default: 69 s.FailNow("expected expired") 70 } 71 } 72 73 func (s *RediaronTestSuite) TestEphemeralFailedAsPutAlready() { 74 ctx := context.Background() 75 path := "/ident" 76 heartbeat := time.Second 77 expiry, stop, err := s.rediaron.StartEphemeral(ctx, path, heartbeat) 78 s.NoError(err) 79 s.NotNil(stop) 80 s.NotNil(expiry) 81 82 defer stop() 83 84 _, _, err = s.rediaron.StartEphemeral(ctx, path, heartbeat) 85 s.Error(err) 86 } 87 88 func TestEphemeralMustRevokeAfterKeepaliveFailed(t *testing.T) { 89 assert := assert.New(t) 90 91 s, err := miniredis.Run() 92 if err != nil { 93 t.Fail() 94 } 95 defer s.Close() 96 97 cli := redis.NewClient(&redis.Options{ 98 Addr: s.Addr(), 99 DB: 0, 100 }) 101 defer cli.Close() 102 103 pool, _ := utils.NewPool(10000) 104 105 rediaron := &Rediaron{ 106 cli: cli, 107 pool: pool, 108 } 109 110 ctx := context.Background() 111 path := "/ident" 112 expiry, stop, err := rediaron.StartEphemeral(ctx, path, time.Millisecond) 113 114 assert.NoError(err) 115 assert.NotNil(stop) 116 assert.NotNil(expiry) 117 118 cli.Close() 119 120 select { 121 case <-expiry: 122 case <-time.After(time.Second * 8): 123 assert.FailNow("%s should had been removed", path) 124 } 125 }