@@ -166,24 +166,38 @@ func (bkr *GRPCBroker) Subscribe(subReq *pbv1.SubscriptionRequest, subServer pbv
166166 ctx , cancel := context .WithCancel (subServer .Context ())
167167 defer cancel ()
168168
169- sendCh := make (chan * pbv1.CloudEvent , 100 )
169+ // TODO make the channel size configurable
170+ eventCh := make (chan * pbv1.CloudEvent , 100 )
171+ heartbeatCh := make (chan * pbv1.CloudEvent , 10 )
170172 sendErrCh := make (chan error , 1 )
171173
174+ // send events
175+ // The grpc send is not concurrency safe and non-blocking, see: https://github.com/grpc/grpc-go/blob/v1.75.1/stream.go#L1571
176+ // Return the error without wrapping, as it includes the gRPC error code and message for further handling.
177+ // For unrecoverable errors, such as a connection closed by an intermediate proxy, push the error to subscriber's
178+ // error channel to unregister the subscriber.
172179 go func () {
173180 for {
174181 select {
175182 case <- ctx .Done ():
176183 return
177- case evt , ok := <- sendCh :
178- if ! ok {
184+ case evt := <- heartbeatCh :
185+ if err := subServer .Send (evt ); err != nil {
186+ klog .Errorf ("failed to send heartbeat: %v" , err )
187+ // Unblock producers (handler select) and exit heartbeat ticker.
188+ cancel ()
189+ select {
190+ case sendErrCh <- err :
191+ default :
192+ }
179193 return
180194 }
195+ case evt := <- eventCh :
181196 if err := subServer .Send (evt ); err != nil {
182197 klog .Errorf ("failed to send event: %v" , err )
198+ // Unblock producers (handler select) and exit heartbeat ticker.
199+ cancel ()
183200 select {
184- // Return the error without wrapping, as it includes the gRPC error code and message for further handling.
185- // For unrecoverable errors, such as a connection closed by an intermediate proxy, push the error to subscriber's
186- // error channel to unregister the subscriber.
187201 case sendErrCh <- err :
188202 default :
189203 }
@@ -204,7 +218,7 @@ func (bkr *GRPCBroker) Subscribe(subReq *pbv1.SubscriptionRequest, subServer pbv
204218 // send the cloudevent to the subscriber
205219 klog .V (4 ).Infof ("sending the event to spec subscribers, %s" , evt .Context )
206220 select {
207- case sendCh <- pbEvt :
221+ case eventCh <- pbEvt :
208222 case <- ctx .Done ():
209223 return status .Error (codes .Unavailable , "stream context canceled" )
210224 }
@@ -226,7 +240,7 @@ func (bkr *GRPCBroker) Subscribe(subReq *pbv1.SubscriptionRequest, subServer pbv
226240 }
227241
228242 select {
229- case sendCh <- heartbeat :
243+ case heartbeatCh <- heartbeat :
230244 default :
231245 klog .Warning ("send channel is full, dropping heartbeat" )
232246 }
0 commit comments