@@ -79,7 +79,7 @@ type ConnectionListener interface {
7979type Connection interface {
8080 SendRequest (requestID uint64 , req * pb.BaseCommand , callback func (* pb.BaseCommand , error ))
8181 SendRequestNoWait (req * pb.BaseCommand ) error
82- WriteData (ctx context.Context , data Buffer )
82+ WriteData (ctx context.Context , data Buffer ) error
8383 RegisterListener (id uint64 , listener ConnectionListener ) error
8484 UnregisterListener (id uint64 )
8585 AddConsumeHandler (id uint64 , handler ConsumerHandler ) error
@@ -456,26 +456,38 @@ func (c *connection) runPingCheck(pingCheckTicker *time.Ticker) {
456456 }
457457}
458458
459- func (c * connection ) WriteData (ctx context.Context , data Buffer ) {
459+ func (c * connection ) WriteData (ctx context.Context , data Buffer ) error {
460+ // If the connection is closed, we should not write on it
461+ if c .getState () != connectionReady {
462+ c .log .Debug ("Connection was already closed" )
463+ return errConnectionClosed
464+ }
465+
460466 select {
461467 case c .writeRequestsCh <- & dataRequest {ctx : ctx , data : data }:
462468 // Channel is not full
463- return
469+ return nil
464470 case <- ctx .Done ():
465471 c .log .Debug ("Write data context cancelled" )
466- return
472+ return ctx . Err ()
467473 default :
468474 // Channel full, fallback to probe if connection is closed
469475 }
470476
477+ // check if the connection is closed again
478+ if c .getState () != connectionReady {
479+ c .log .Debug ("Connection was already closed" )
480+ return errConnectionClosed
481+ }
482+
471483 for {
472484 select {
473485 case c .writeRequestsCh <- & dataRequest {ctx : ctx , data : data }:
474486 // Successfully wrote on the channel
475- return
487+ return nil
476488 case <- ctx .Done ():
477489 c .log .Debug ("Write data context cancelled" )
478- return
490+ return ctx . Err ()
479491 case <- time .After (100 * time .Millisecond ):
480492 // The channel is either:
481493 // 1. blocked, in which case we need to wait until we have space
@@ -484,7 +496,7 @@ func (c *connection) WriteData(ctx context.Context, data Buffer) {
484496
485497 if c .getState () != connectionReady {
486498 c .log .Debug ("Connection was already closed" )
487- return
499+ return errConnectionClosed
488500 }
489501 }
490502 }
0 commit comments