@@ -35,7 +35,7 @@ func NewWebSocketController(
3535 logger : logger .With ().Str ("component" , "websocket-controller" ).Logger (),
3636 config : config ,
3737 conn : conn ,
38- communicationChannel : make (chan interface {}, 10 ), //TODO: should it be buffered chan?
38+ communicationChannel : make (chan interface {}), //TODO: should it be buffered chan?
3939 dataProviders : concurrentmap .New [uuid.UUID , dp.DataProvider ](),
4040 dataProvidersFactory : factory ,
4141 shutdownOnce : sync.Once {},
@@ -46,6 +46,7 @@ func NewWebSocketController(
4646func (c * Controller ) HandleConnection (ctx context.Context ) {
4747 //TODO: configure the connection with ping-pong and deadlines
4848 //TODO: spin up a response limit tracker routine
49+ defer c .shutdownConnection ()
4950 go c .readMessages (ctx )
5051 c .writeMessages (ctx )
5152}
@@ -54,8 +55,6 @@ func (c *Controller) HandleConnection(ctx context.Context) {
5455// The communication channel is filled by data providers. Besides, the response limit tracker is involved in
5556// write message regulation
5657func (c * Controller ) writeMessages (ctx context.Context ) {
57- defer c .shutdownConnection ()
58-
5958 for {
6059 select {
6160 case <- ctx .Done ():
@@ -86,8 +85,6 @@ func (c *Controller) writeMessages(ctx context.Context) {
8685// readMessages continuously reads messages from a client WebSocket connection,
8786// processes each message, and handles actions based on the message type.
8887func (c * Controller ) readMessages (ctx context.Context ) {
89- defer c .shutdownConnection ()
90-
9188 for {
9289 msg , err := c .readMessage ()
9390 if err != nil {
@@ -188,7 +185,12 @@ func (c *Controller) handleSubscribe(ctx context.Context, msg models.SubscribeMe
188185 Topic : dp .Topic (),
189186 ID : dp .ID ().String (),
190187 }
191- c .communicationChannel <- response
188+
189+ select {
190+ case <- ctx .Done ():
191+ return
192+ case c .communicationChannel <- response :
193+ }
192194
193195 dp .Run (ctx )
194196}
@@ -216,8 +218,6 @@ func (c *Controller) handleListSubscriptions(ctx context.Context, msg models.Lis
216218func (c * Controller ) shutdownConnection () {
217219 c .shutdownOnce .Do (func () {
218220 defer func () {
219- close (c .communicationChannel )
220-
221221 if err := c .conn .Close (); err != nil {
222222 c .logger .Warn ().Err (err ).Msg ("error closing connection" )
223223 }
0 commit comments