edge/pkg/http/sockjs.go

232 lines
4.9 KiB
Go
Raw Normal View History

2023-02-09 12:16:36 +01:00
package http
import (
"context"
"encoding/json"
"net/http"
"forge.cadoles.com/arcad/edge/pkg/module"
"github.com/igm/sockjs-go/v3/sockjs"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
const (
statusChannelClosed = iota
)
const (
ContextKeySessionID module.ContextKey = "sessionId"
ContextKeyOriginRequest module.ContextKey = "originRequest"
)
2023-02-09 12:16:36 +01:00
func (h *Handler) handleSockJS(w http.ResponseWriter, r *http.Request) {
h.mutex.RLock()
defer h.mutex.RUnlock()
h.sockjs.ServeHTTP(w, r)
}
func (h *Handler) handleSockJSSession(sess sockjs.Session) {
ctx := logger.With(sess.Request().Context(),
logger.F("sessionID", sess.ID()),
)
logger.Debug(ctx, "new sockjs session")
defer func() {
if sess.GetSessionState() == sockjs.SessionActive {
if err := sess.Close(statusChannelClosed, "channel closed"); err != nil {
logger.Error(ctx, "could not close sockjs session", logger.CapturedE(errors.WithStack(err)))
2023-02-09 12:16:36 +01:00
}
}
}()
2023-11-28 16:35:49 +01:00
go h.handleOutgoingMessages(ctx, sess)
h.handleIncomingMessages(ctx, sess)
2023-02-09 12:16:36 +01:00
}
2023-11-28 16:35:49 +01:00
func (h *Handler) handleOutgoingMessages(ctx context.Context, sess sockjs.Session) {
envelopes, err := h.bus.Subscribe(ctx, AddressOutgoingMessage)
2023-02-09 12:16:36 +01:00
if err != nil {
panic(errors.WithStack(err))
}
defer func() {
2023-11-28 16:35:49 +01:00
h.bus.Unsubscribe(AddressOutgoingMessage, envelopes)
2023-02-09 12:16:36 +01:00
logger.Debug(ctx, "unsubscribed")
if sess.GetSessionState() != sockjs.SessionActive {
return
}
if err := sess.Close(statusChannelClosed, "channel closed"); err != nil {
logger.Error(ctx, "could not close sockjs session", logger.CapturedE(errors.WithStack(err)))
2023-02-09 12:16:36 +01:00
}
}()
for {
select {
case <-ctx.Done():
return
2023-11-28 16:35:49 +01:00
case env := <-envelopes:
outgoingMessage, ok := env.Message().(*OutgoingMessage)
2023-02-09 12:16:36 +01:00
if !ok {
logger.Error(
ctx,
2023-11-28 16:35:49 +01:00
"unexpected outgoing message",
logger.F("message", env.Message()),
2023-02-09 12:16:36 +01:00
)
}
2023-11-28 16:35:49 +01:00
isDest := outgoingMessage.SessionID == "" || outgoingMessage.SessionID == sess.ID()
2023-02-09 12:16:36 +01:00
if !isDest {
continue
}
2023-11-28 16:35:49 +01:00
payload, err := json.Marshal(outgoingMessage.Data)
2023-02-09 12:16:36 +01:00
if err != nil {
logger.Error(
ctx,
"could not encode message",
logger.CapturedE(errors.WithStack(err)),
2023-02-09 12:16:36 +01:00
)
continue
}
message := NewWebsocketMessage(
WebsocketMessageTypeMessage,
json.RawMessage(payload),
)
data, err := json.Marshal(message)
if err != nil {
logger.Error(
ctx,
"could not encode message",
logger.CapturedE(errors.WithStack(err)),
2023-02-09 12:16:36 +01:00
)
continue
}
logger.Debug(ctx, "sending message")
// Send message
if err := sess.Send(string(data)); err != nil {
logger.Error(
ctx,
"could not send message",
logger.CapturedE(errors.WithStack(err)),
2023-02-09 12:16:36 +01:00
)
}
}
}
}
2023-11-28 16:35:49 +01:00
func (h *Handler) handleIncomingMessages(ctx context.Context, sess sockjs.Session) {
2023-02-09 12:16:36 +01:00
for {
select {
case <-ctx.Done():
logger.Debug(ctx, "context done")
return
default:
logger.Debug(ctx, "waiting for websocket data")
data, err := sess.RecvCtx(ctx)
if err != nil {
2023-11-28 16:35:49 +01:00
if errors.Is(err, sockjs.ErrSessionNotOpen) || errors.Is(err, context.Canceled) {
2023-02-09 12:16:36 +01:00
break
}
logger.Error(
ctx,
"could not read message",
logger.CapturedE(errors.WithStack(err)),
2023-02-09 12:16:36 +01:00
)
break
}
logger.Debug(ctx, "websocket data received", logger.F("data", data))
message := &WebsocketMessage{}
if err := json.Unmarshal([]byte(data), message); err != nil {
logger.Error(
ctx,
"could not decode message",
logger.CapturedE(errors.WithStack(err)),
2023-02-09 12:16:36 +01:00
)
break
}
switch {
case message.Type == WebsocketMessageTypeMessage:
2023-11-28 16:35:49 +01:00
var payload map[string]any
2023-02-09 12:16:36 +01:00
if err := json.Unmarshal(message.Payload, &payload); err != nil {
logger.Error(
ctx,
"could not decode payload",
logger.CapturedE(errors.WithStack(err)),
2023-02-09 12:16:36 +01:00
)
return
}
ctx := logger.With(ctx, logger.F("payload", payload))
ctx = module.WithContext(ctx, map[module.ContextKey]any{
ContextKeySessionID: sess.ID(),
ContextKeyOriginRequest: sess.Request(),
2023-02-09 12:16:36 +01:00
})
2023-11-28 16:35:49 +01:00
incomingMessage := NewIncomingMessageEnvelope(ctx, payload)
2023-02-09 12:16:36 +01:00
2023-11-28 16:35:49 +01:00
logger.Debug(ctx, "publishing new incoming message", logger.F("message", incomingMessage))
2023-02-09 12:16:36 +01:00
2023-11-28 16:35:49 +01:00
if err := h.bus.Publish(incomingMessage); err != nil {
2023-02-09 12:16:36 +01:00
logger.Error(ctx, "could not publish message",
logger.CapturedE(errors.WithStack(err)),
2023-11-28 16:35:49 +01:00
logger.F("message", incomingMessage),
2023-02-09 12:16:36 +01:00
)
return
}
default:
logger.Error(
ctx,
"unsupported message type",
logger.F("messageType", message.Type),
)
}
}
}
}
const (
WebsocketMessageTypeMessage = "message"
)
type WebsocketMessage struct {
Type string `json:"t"`
Payload json.RawMessage `json:"p"`
}
type WebsocketMessagePayload struct {
Data map[string]interface{} `json:"d"`
}
func NewWebsocketMessage(dataType string, payload json.RawMessage) *WebsocketMessage {
return &WebsocketMessage{
Type: dataType,
Payload: payload,
}
}