Skip to content

Commit 8d4710b

Browse files
committed
supporting heartbeat in cloudevents subscribe stream
Signed-off-by: Wei Liu <liuweixa@redhat.com>
1 parent 7d8041a commit 8d4710b

13 files changed

Lines changed: 437 additions & 27 deletions

File tree

pkg/cloudevents/generic/options/grpc/agentoptions.go

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,7 @@ func (o *grpcAgentOptions) WithContext(ctx context.Context, evtCtx cloudevents.E
3434
}
3535

3636
func (o *grpcAgentOptions) Protocol(ctx context.Context, dataType types.CloudEventsDataType) (options.CloudEventsProtocol, error) {
37-
receiver, err := o.GetCloudEventsProtocol(
38-
ctx,
39-
func(err error) {
40-
o.errorChan <- err
41-
},
37+
opts := []protocol.Option{
4238
protocol.WithSubscribeOption(&protocol.SubscribeOption{
4339
// TODO: Update this code to determine the subscription source for the agent client.
4440
// Currently, the grpc agent client is not utilized, and the 'Source' field serves
@@ -47,6 +43,19 @@ func (o *grpcAgentOptions) Protocol(ctx context.Context, dataType types.CloudEve
4743
ClusterName: o.clusterName,
4844
DataType: dataType.String(),
4945
}),
46+
protocol.WithReconnectErrorChan(o.errorChan),
47+
}
48+
49+
if o.ServerHealthinessTimeout != nil {
50+
opts = append(opts, protocol.WithServerHealthinessTimeout(*o.ServerHealthinessTimeout))
51+
}
52+
53+
receiver, err := o.GetCloudEventsProtocol(
54+
ctx,
55+
func(err error) {
56+
o.errorChan <- err
57+
},
58+
opts...,
5059
)
5160
if err != nil {
5261
return nil, err

pkg/cloudevents/generic/options/grpc/options.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,8 @@ func (d *GRPCDialer) Close() error {
114114
// GRPCOptions holds the options that are used to build gRPC client.
115115
type GRPCOptions struct {
116116
Dialer *GRPCDialer
117+
118+
ServerHealthinessTimeout *time.Duration
117119
}
118120

119121
// GRPCConfig holds the information needed to build connect to gRPC server as a given user.
@@ -130,6 +132,10 @@ type GRPCConfig struct {
130132

131133
// keepalive options
132134
KeepAliveConfig KeepAliveConfig `json:"keepAliveConfig,omitempty" yaml:"keepAliveConfig,omitempty"`
135+
136+
// serverHealthinessTimeout is the max duration that client will reconnect if no server healthiness status is
137+
// received in this duration, if it is not set, client will not reconnect when health message is received
138+
ServerHealthinessTimeout *time.Duration `json:"serverHealthinessTimeout,omitempty" yaml:"serverHealthinessTimeout,omitempty"`
133139
}
134140

135141
// KeepAliveConfig holds the keepalive options for the gRPC client.
@@ -241,6 +247,7 @@ func BuildGRPCOptionsFromFlags(configPath string) (*GRPCOptions, error) {
241247
}
242248
}
243249

250+
options.ServerHealthinessTimeout = config.ServerHealthinessTimeout
244251
return options, nil
245252
}
246253

pkg/cloudevents/generic/options/grpc/options_test.go

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
"github.com/google/go-cmp/cmp"
99
"github.com/google/go-cmp/cmp/cmpopts"
10+
"k8s.io/utils/ptr"
1011
clienttesting "open-cluster-management.io/sdk-go/pkg/testing"
1112
)
1213

@@ -36,7 +37,7 @@ func TestBuildGRPCOptionsFromFlags(t *testing.T) {
3637
name: "customized options",
3738
config: "{\"url\":\"test\"}",
3839
expectedOptions: &GRPCOptions{
39-
&GRPCDialer{
40+
Dialer: &GRPCDialer{
4041
URL: "test",
4142
KeepAliveOptions: KeepAliveOptions{
4243
Enable: false,
@@ -51,7 +52,7 @@ func TestBuildGRPCOptionsFromFlags(t *testing.T) {
5152
name: "customized options with yaml format",
5253
config: "url: test",
5354
expectedOptions: &GRPCOptions{
54-
&GRPCDialer{
55+
Dialer: &GRPCDialer{
5556
URL: "test",
5657
KeepAliveOptions: KeepAliveOptions{
5758
Enable: false,
@@ -66,7 +67,7 @@ func TestBuildGRPCOptionsFromFlags(t *testing.T) {
6667
name: "customized options with keepalive",
6768
config: "{\"url\":\"test\",\"keepAliveConfig\":{\"enable\":true,\"time\":10s,\"timeout\":5s,\"permitWithoutStream\":true}}",
6869
expectedOptions: &GRPCOptions{
69-
&GRPCDialer{
70+
Dialer: &GRPCDialer{
7071
URL: "test",
7172
KeepAliveOptions: KeepAliveOptions{
7273
Enable: true,
@@ -77,6 +78,22 @@ func TestBuildGRPCOptionsFromFlags(t *testing.T) {
7778
},
7879
},
7980
},
81+
{
82+
name: "customized options with ServerHealthinessTimeout",
83+
config: "{\"url\":\"test\",\"serverHealthinessTimeout\":\"10s\"}",
84+
expectedOptions: &GRPCOptions{
85+
Dialer: &GRPCDialer{
86+
URL: "test",
87+
KeepAliveOptions: KeepAliveOptions{
88+
Enable: false,
89+
Time: 30 * time.Second,
90+
Timeout: 10 * time.Second,
91+
PermitWithoutStream: false,
92+
},
93+
},
94+
ServerHealthinessTimeout: ptr.To(10 * time.Second),
95+
},
96+
},
8097
}
8198

8299
for _, c := range cases {

pkg/cloudevents/generic/options/grpc/protocol/message.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ const (
1919
prefix = "ce-"
2020
contenttype = "contenttype"
2121
// dataSchema = "dataschema"
22-
subject = "subject"
23-
time = "time"
22+
subject = "subject"
23+
timestamp = "time"
2424
)
2525

2626
var specs = spec.WithPrefix(prefix)

pkg/cloudevents/generic/options/grpc/protocol/option.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package protocol
22

33
import (
44
"fmt"
5+
"time"
56
)
67

78
// Option is the function signature
@@ -24,3 +25,23 @@ func WithSubscribeOption(subscribeOpt *SubscribeOption) Option {
2425
return nil
2526
}
2627
}
28+
29+
func WithReconnectErrorChan(errorChan chan error) Option {
30+
return func(p *Protocol) error {
31+
if errorChan == nil {
32+
return fmt.Errorf("the errorChan must not be nil")
33+
}
34+
p.reconnectErrorChan = errorChan
35+
return nil
36+
}
37+
}
38+
39+
func WithServerHealthinessTimeout(timeout time.Duration) Option {
40+
return func(p *Protocol) error {
41+
if timeout <= 0 {
42+
p.serverHealthinessTimeout = 20 * time.Second // by default, using 20s
43+
}
44+
p.serverHealthinessTimeout = timeout
45+
return nil
46+
}
47+
}
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
package protocol
2+
3+
import (
4+
"context"
5+
"net"
6+
"testing"
7+
"time"
8+
9+
"google.golang.org/grpc/credentials/insecure"
10+
11+
"google.golang.org/grpc"
12+
"google.golang.org/grpc/test/bufconn"
13+
"google.golang.org/protobuf/types/known/emptypb"
14+
15+
pbv1 "open-cluster-management.io/sdk-go/pkg/cloudevents/generic/options/grpc/protobuf/v1"
16+
"open-cluster-management.io/sdk-go/pkg/cloudevents/server/grpc/health"
17+
)
18+
19+
const bufSize = 1024 * 1024
20+
21+
// mockCloudEventService implements a basic mock of CloudEventServiceServer
22+
type mockCloudEventService struct {
23+
pbv1.UnimplementedCloudEventServiceServer
24+
healthEnabled bool
25+
}
26+
27+
func (m *mockCloudEventService) Publish(ctx context.Context, req *pbv1.PublishRequest) (*emptypb.Empty, error) {
28+
return &emptypb.Empty{}, nil
29+
}
30+
31+
func (m *mockCloudEventService) Subscribe(req *pbv1.SubscriptionRequest, stream pbv1.CloudEventService_SubscribeServer) error {
32+
if m.healthEnabled {
33+
go health.Heartbeat(stream.Context(), stream, 500*time.Millisecond)
34+
}
35+
// Keep the stream open for testing
36+
<-stream.Context().Done()
37+
return stream.Context().Err()
38+
}
39+
40+
func setupMockServer(t *testing.T, healthEnabled bool) (*grpc.ClientConn, func()) {
41+
lis := bufconn.Listen(bufSize)
42+
s := grpc.NewServer()
43+
44+
// Register cloud event service
45+
pbv1.RegisterCloudEventServiceServer(s, &mockCloudEventService{healthEnabled: healthEnabled})
46+
47+
go func() {
48+
if err := s.Serve(lis); err != nil {
49+
t.Logf("Server exited with error: %v", err)
50+
}
51+
}()
52+
53+
// Wait for server to start accepting connections
54+
time.Sleep(50 * time.Millisecond)
55+
56+
bufDialer := func(context.Context, string) (net.Conn, error) {
57+
return lis.Dial()
58+
}
59+
60+
conn, err := grpc.NewClient("passthrough:///bufnet",
61+
grpc.WithTransportCredentials(insecure.NewCredentials()),
62+
grpc.WithContextDialer(bufDialer))
63+
64+
if err != nil {
65+
t.Fatalf("Failed to create client: %v", err)
66+
}
67+
68+
cleanup := func() {
69+
conn.Close()
70+
s.Stop()
71+
}
72+
73+
return conn, cleanup
74+
}
75+
76+
func TestProtocol_Success(t *testing.T) {
77+
conn, cleanup := setupMockServer(t, true)
78+
defer cleanup()
79+
80+
reconnectErrorChan := make(chan error, 1)
81+
p, err := NewProtocol(
82+
conn,
83+
WithSubscribeOption(&SubscribeOption{
84+
Source: "test",
85+
ClusterName: "test-cluster",
86+
DataType: "io.open-cluster-management.test",
87+
}),
88+
WithReconnectErrorChan(reconnectErrorChan),
89+
WithServerHealthinessTimeout(5*time.Second),
90+
)
91+
if err != nil {
92+
t.Fatal(err)
93+
}
94+
95+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
96+
defer cancel()
97+
98+
go func() {
99+
if err := p.OpenInbound(ctx); err != nil {
100+
p.reconnectErrorChan <- err
101+
}
102+
}()
103+
104+
// Should not receive any error since health check was successful
105+
select {
106+
case err := <-p.reconnectErrorChan:
107+
t.Errorf("Unexpected error from health check: %v", err)
108+
case <-time.After(2 * time.Second):
109+
// Expected - no error
110+
}
111+
}
112+
113+
func TestProtocol_Timeout(t *testing.T) {
114+
conn, cleanup := setupMockServer(t, false) // No health service
115+
defer cleanup()
116+
117+
reconnectErrorChan := make(chan error, 1)
118+
p, err := NewProtocol(
119+
conn,
120+
WithSubscribeOption(&SubscribeOption{
121+
Source: "test",
122+
ClusterName: "test-cluster",
123+
DataType: "io.open-cluster-management.test",
124+
}),
125+
WithReconnectErrorChan(reconnectErrorChan),
126+
WithServerHealthinessTimeout(2*time.Second),
127+
)
128+
if err != nil {
129+
t.Fatal(err)
130+
}
131+
132+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
133+
defer cancel()
134+
135+
go func() {
136+
if err := p.OpenInbound(ctx); err != nil {
137+
p.reconnectErrorChan <- err
138+
}
139+
}()
140+
141+
// Should receive an error due to health service not being available
142+
select {
143+
case err := <-p.reconnectErrorChan:
144+
if err == nil {
145+
t.Errorf("Expected health check error, but got nil %v", err)
146+
}
147+
case <-time.After(3 * time.Second):
148+
t.Error("Expected health check error within timeout")
149+
}
150+
}

0 commit comments

Comments
 (0)