summaryrefslogtreecommitdiff
path: root/plugins/websockets/executor/executor.go
blob: 5f904d266583245f957f7422bbe4a9363f9c8185 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package executor

import (
	"fmt"
	"net/http"
	"sync"

	json "github.com/json-iterator/go"
	"github.com/spiral/errors"
	websocketsv1 "github.com/spiral/roadrunner/v2/pkg/proto/websockets/v1beta"
	"github.com/spiral/roadrunner/v2/pkg/pubsub"
	"github.com/spiral/roadrunner/v2/plugins/logger"
	"github.com/spiral/roadrunner/v2/plugins/websockets/commands"
	"github.com/spiral/roadrunner/v2/plugins/websockets/connection"
	"github.com/spiral/roadrunner/v2/plugins/websockets/validator"
)

type Response struct {
	Topic   string   `json:"topic"`
	Payload []string `json:"payload"`
}

type Executor struct {
	sync.Mutex
	conn *connection.Connection
	log  logger.Logger

	// associated connection ID
	connID string

	// map with the pubsub drivers
	pubsub       map[string]pubsub.PubSub
	actualTopics map[string]struct{}

	req             *http.Request
	accessValidator validator.AccessValidatorFn
}

// NewExecutor creates protected connection and starts command loop
func NewExecutor(conn *connection.Connection, log logger.Logger,
	connID string, pubsubs map[string]pubsub.PubSub, av validator.AccessValidatorFn, r *http.Request) *Executor {
	return &Executor{
		conn:            conn,
		connID:          connID,
		log:             log,
		pubsub:          pubsubs,
		accessValidator: av,
		actualTopics:    make(map[string]struct{}, 10),
		req:             r,
	}
}

func (e *Executor) StartCommandLoop() error { //nolint:gocognit
	const op = errors.Op("executor_command_loop")
	for {
		mt, data, err := e.conn.Read()
		if err != nil {
			if mt == -1 {
				e.log.Info("socket was closed", "reason", err, "message type", mt)
				return nil
			}

			return errors.E(op, err)
		}

		msg := &websocketsv1.Message{}

		err = json.Unmarshal(data, msg)
		if err != nil {
			e.log.Error("error unmarshal message", "error", err)
			continue
		}

		// nil message, continue
		if msg == nil {
			e.log.Warn("get nil message, skipping")
			continue
		}

		switch msg.Command {
		// handle leave
		case commands.Join:
			e.log.Debug("get join command", "msg", msg)

			val, err := e.accessValidator(e.req, msg.Topics...)
			if err != nil {
				if val != nil {
					e.log.Debug("validation error", "status", val.Status, "headers", val.Header, "body", val.Body)
				}

				resp := &Response{
					Topic:   "#join",
					Payload: msg.Topics,
				}

				packet, errJ := json.Marshal(resp)
				if errJ != nil {
					e.log.Error("error marshal the body", "error", errJ)
					return errors.E(op, fmt.Errorf("%v,%v", err, errJ))
				}

				errW := e.conn.Write(packet)
				if errW != nil {
					e.log.Error("error writing payload to the connection", "payload", packet, "error", errW)
					return errors.E(op, fmt.Errorf("%v,%v", err, errW))
				}

				continue
			}

			resp := &Response{
				Topic:   "@join",
				Payload: msg.Topics,
			}

			packet, err := json.Marshal(resp)
			if err != nil {
				e.log.Error("error marshal the body", "error", err)
				return errors.E(op, err)
			}

			err = e.conn.Write(packet)
			if err != nil {
				e.log.Error("error writing payload to the connection", "payload", packet, "error", err)
				return errors.E(op, err)
			}

			// subscribe to the topic
			if br, ok := e.pubsub[msg.Broker]; ok {
				err = e.Set(br, msg.Topics)
				if err != nil {
					return errors.E(op, err)
				}
			}

		// handle leave
		case commands.Leave:
			e.log.Debug("get leave command", "msg", msg)

			// prepare response
			resp := &Response{
				Topic:   "@leave",
				Payload: msg.Topics,
			}

			packet, err := json.Marshal(resp)
			if err != nil {
				e.log.Error("error marshal the body", "error", err)
				return errors.E(op, err)
			}

			err = e.conn.Write(packet)
			if err != nil {
				e.log.Error("error writing payload to the connection", "payload", packet, "error", err)
				return errors.E(op, err)
			}

			if br, ok := e.pubsub[msg.Broker]; ok {
				err = e.Leave(br, msg.Topics)
				if err != nil {
					return errors.E(op, err)
				}
			}

		case commands.Headers:

		default:
			e.log.Warn("unknown command", "command", msg.Command)
		}
	}
}

func (e *Executor) Set(br pubsub.PubSub, topics []string) error {
	// associate connection with topics
	err := br.Subscribe(e.connID, topics...)
	if err != nil {
		e.log.Error("error subscribing to the provided topics", "topics", topics, "error", err.Error())
		// in case of error, unsubscribe connection from the dead topics
		_ = br.Unsubscribe(e.connID, topics...)
		return err
	}

	// save topics for the connection
	for i := 0; i < len(topics); i++ {
		e.actualTopics[topics[i]] = struct{}{}
	}

	return nil
}

func (e *Executor) Leave(br pubsub.PubSub, topics []string) error {
	// remove associated connections from the storage
	err := br.Unsubscribe(e.connID, topics...)
	if err != nil {
		e.log.Error("error subscribing to the provided topics", "topics", topics, "error", err.Error())
		return err
	}

	// remove topics for the connection
	for i := 0; i < len(topics); i++ {
		delete(e.actualTopics, topics[i])
	}

	return nil
}

func (e *Executor) CleanUp() {
	// unsubscribe particular connection from the topics
	for topic := range e.actualTopics {
		// here
		for _, ps := range e.pubsub {
			_ = ps.Unsubscribe(e.connID, topic)
		}
	}

	// clean up the actualTopics data
	for k := range e.actualTopics {
		delete(e.actualTopics, k)
	}
}