2023-04-27 09:03:40 +08:00
|
|
|
package writer
|
|
|
|
|
|
|
|
import (
|
2024-06-29 03:53:11 +08:00
|
|
|
"bytes"
|
2024-06-25 21:27:44 +08:00
|
|
|
"encoding/json"
|
2023-12-15 01:01:47 +08:00
|
|
|
"github.com/iMDT/bbb-graphql-middleware/internal/common"
|
2023-04-27 09:03:40 +08:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"nhooyr.io/websocket"
|
2024-03-13 07:12:55 +08:00
|
|
|
"sync"
|
2023-04-27 09:03:40 +08:00
|
|
|
)
|
|
|
|
|
2024-06-25 21:27:44 +08:00
|
|
|
func BrowserConnectionWriter(
|
2024-07-06 00:35:08 +08:00
|
|
|
browserConnection *common.BrowserConnection,
|
2024-06-25 21:27:44 +08:00
|
|
|
wg *sync.WaitGroup) {
|
2024-07-06 00:35:08 +08:00
|
|
|
log := log.WithField("_routine", "BrowserConnectionWriter").WithField("browserConnectionId", browserConnection.Id)
|
2023-09-07 22:54:27 +08:00
|
|
|
defer log.Debugf("finished")
|
2023-09-30 07:05:23 +08:00
|
|
|
log.Debugf("starting")
|
|
|
|
defer wg.Done()
|
2023-04-27 09:03:40 +08:00
|
|
|
|
|
|
|
RangeLoop:
|
|
|
|
for {
|
|
|
|
select {
|
2024-07-06 00:35:08 +08:00
|
|
|
case <-browserConnection.Context.Done():
|
2024-03-13 07:12:55 +08:00
|
|
|
log.Debug("Browser context cancelled.")
|
2023-04-27 09:03:40 +08:00
|
|
|
break RangeLoop
|
2024-07-06 00:35:08 +08:00
|
|
|
case toBrowserMessage := <-browserConnection.FromHasuraToBrowserChannel.ReceiveChannel():
|
2023-04-27 09:03:40 +08:00
|
|
|
{
|
2024-03-13 07:12:55 +08:00
|
|
|
if toBrowserMessage == nil {
|
2024-07-06 00:35:08 +08:00
|
|
|
if browserConnection.FromHasuraToBrowserChannel.Closed() {
|
2024-03-13 21:35:51 +08:00
|
|
|
break RangeLoop
|
|
|
|
}
|
2024-03-13 07:12:55 +08:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-07-01 08:26:02 +08:00
|
|
|
log.Tracef("sending to browser: %s", string(toBrowserMessage))
|
2024-07-06 00:35:08 +08:00
|
|
|
err := browserConnection.Websocket.Write(browserConnection.Context, websocket.MessageText, toBrowserMessage)
|
2023-04-27 09:03:40 +08:00
|
|
|
if err != nil {
|
2024-03-18 21:58:53 +08:00
|
|
|
log.Debugf("Browser is disconnected, skipping writing of ws message: %v", err)
|
2023-04-27 09:03:40 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// After the error is sent to client, close its connection
|
|
|
|
// Authentication hook unauthorized this request
|
2024-06-29 03:53:11 +08:00
|
|
|
if bytes.Contains(toBrowserMessage, []byte("connection_error")) {
|
2024-06-25 21:27:44 +08:00
|
|
|
type HasuraMessage struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
}
|
|
|
|
var hasuraMessage HasuraMessage
|
|
|
|
_ = json.Unmarshal(toBrowserMessage, &hasuraMessage)
|
|
|
|
if hasuraMessage.Type == "connection_error" {
|
2024-07-06 00:35:08 +08:00
|
|
|
_ = browserConnection.Websocket.Close(websocket.StatusInternalError, string(toBrowserMessage))
|
2024-06-25 21:27:44 +08:00
|
|
|
}
|
2023-04-27 09:03:40 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|