github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/store/etcdv3/meta/ephemeral_test.go (about) 1 package meta 2 3 import ( 4 "context" 5 "testing" 6 "time" 7 8 "github.com/stretchr/testify/require" 9 ) 10 11 func TestEphemeralDeregister(t *testing.T) { 12 m := NewEmbeddedETCD(t) 13 14 ctx := context.Background() 15 path := "/ident" 16 heartbeat := time.Millisecond 17 expiry, stop, err := m.StartEphemeral(ctx, path, heartbeat) 18 require.NoError(t, err) 19 require.NotNil(t, stop) 20 require.NotNil(t, expiry) 21 22 kv, err := m.GetOne(ctx, path) 23 require.NoError(t, err) 24 require.Equal(t, path, string(kv.Key)) 25 26 stop() 27 kv, err = m.GetOne(ctx, path) 28 require.Error(t, err) 29 require.Nil(t, kv) 30 } 31 32 func TestEphemeral(t *testing.T) { 33 m := NewEmbeddedETCD(t) 34 35 ctx := context.Background() 36 path := "/ident" 37 heartbeat := time.Millisecond 38 expiry, stop, err := m.StartEphemeral(ctx, path, heartbeat) 39 require.NoError(t, err) 40 require.NotNil(t, stop) 41 require.NotNil(t, expiry) 42 43 kv, err := m.GetOne(ctx, path) 44 require.NoError(t, err) 45 require.Equal(t, path, string(kv.Key)) 46 47 // Makes sure that the ephemeral keeps alived. 48 time.Sleep(heartbeat * 5) 49 kv, err = m.GetOne(ctx, path) 50 require.NoError(t, err) 51 require.Equal(t, path, string(kv.Key)) 52 53 select { 54 case <-expiry: 55 require.FailNow(t, "unexpected expired") 56 default: 57 } 58 59 // Stop and waiting for expiry. 60 stop() 61 time.Sleep(heartbeat * 5) 62 // Ephemeral kv has been removed. 63 kv, err = m.GetOne(ctx, path) 64 require.Error(t, err) // no such path 65 require.Nil(t, kv) 66 67 select { 68 case <-expiry: 69 default: 70 require.FailNow(t, "expected expired") 71 } 72 } 73 74 func TestEphemeralFailedAsPutAlready(t *testing.T) { 75 m := NewEmbeddedETCD(t) 76 77 ctx := context.Background() 78 path := "/ident" 79 heartbeat := time.Millisecond 80 expiry, stop, err := m.StartEphemeral(ctx, path, heartbeat) 81 require.NoError(t, err) 82 require.NotNil(t, stop) 83 require.NotNil(t, expiry) 84 85 defer stop() 86 87 _, _, err = m.StartEphemeral(ctx, path, heartbeat) 88 require.Error(t, err) 89 } 90 91 func TestEphemeralMustRevokeAfterKeepaliveFailed(t *testing.T) { 92 m := NewEmbeddedETCD(t) 93 94 ctx := context.Background() 95 path := "/ident" 96 expiry, stop, err := m.StartEphemeral(ctx, path, time.Millisecond) 97 require.NoError(t, err) 98 require.NotNil(t, stop) 99 require.NotNil(t, expiry) 100 101 stop() 102 // TODO should reconsider here 103 select { 104 case <-expiry: 105 case <-time.After(time.Second * 8): 106 require.FailNow(t, path+" had been removed") 107 } 108 }