summaryrefslogtreecommitdiff
path: root/plugins/websockets/plugin.go
blob: bc5028e6cdcf904218a453ee237e32919956256f (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
package websockets

import (
	"net/http"
	"sync"
	"time"

	"github.com/fasthttp/websocket"
	"github.com/google/uuid"
	endure "github.com/spiral/endure/pkg/container"
	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/pkg/pubsub"
	"github.com/spiral/roadrunner/v2/plugins/config"
	"github.com/spiral/roadrunner/v2/plugins/logger"
	"github.com/spiral/roadrunner/v2/plugins/websockets/connection"
	"github.com/spiral/roadrunner/v2/plugins/websockets/executor"
	"github.com/spiral/roadrunner/v2/plugins/websockets/pool"
	"github.com/spiral/roadrunner/v2/plugins/websockets/storage"
)

const (
	PluginName string = "websockets"
)

type Plugin struct {
	sync.RWMutex
	// Collection with all available pubsubs
	pubsubs map[string]pubsub.PubSub

	Config *Config
	log    logger.Logger

	// global connections map
	connections sync.Map
	storage     *storage.Storage

	workersPool *pool.WorkersPool
}

func (p *Plugin) Init(cfg config.Configurer, log logger.Logger) error {
	const op = errors.Op("websockets_plugin_init")
	if !cfg.Has(PluginName) {
		return errors.E(op, errors.Disabled)
	}

	err := cfg.UnmarshalKey(PluginName, &p.Config)
	if err != nil {
		return errors.E(op, err)
	}

	p.pubsubs = make(map[string]pubsub.PubSub)
	p.log = log
	p.storage = storage.NewStorage()
	p.workersPool = pool.NewWorkersPool(p.storage, &p.connections, log)

	return nil
}

func (p *Plugin) Serve() chan error {
	errCh := make(chan error)

	// run all pubsubs drivers
	for _, v := range p.pubsubs {
		go func(ps pubsub.PubSub) {
			for {
				data, err := ps.Next()
				if err != nil {
					errCh <- err
					return
				}

				if data == nil {
					continue
				}

				p.workersPool.Queue(data)
			}
		}(v)
	}
	return errCh
}

func (p *Plugin) Stop() error {
	p.workersPool.Stop()
	return nil
}

func (p *Plugin) Collects() []interface{} {
	return []interface{}{
		p.GetPublishers,
	}
}

func (p *Plugin) Available() {}

func (p *Plugin) RPC() interface{} {
	return &rpc{
		plugin: p,
		log:    p.log,
	}
}

func (p *Plugin) Name() string {
	return PluginName
}

// GetPublishers collects all pubsubs
func (p *Plugin) GetPublishers(name endure.Named, pub pubsub.PubSub) {
	p.pubsubs[name.Name()] = pub
}

func (p *Plugin) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != p.Config.Path {
			next.ServeHTTP(w, r)
			return
		}

		// connection upgrader
		upgraded := websocket.Upgrader{
			HandshakeTimeout:  time.Second * 60,
			ReadBufferSize:    0,
			WriteBufferSize:   0,
			WriteBufferPool:   nil,
			Subprotocols:      nil,
			Error:             nil,
			CheckOrigin:       nil,
			EnableCompression: false,
		}

		// upgrade connection to websocket connection
		_conn, err := upgraded.Upgrade(w, r, nil)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		safeConn := connection.NewConnection(_conn, p.log)
		defer func() {
			err = safeConn.Close()
			if err != nil {
				p.log.Error("connection close error", "error", err)
			}
		}()

		// generate UUID from the connection
		connectionID := uuid.NewString()
		// store connection
		p.connections.Store(connectionID, safeConn)
		// when exiting - delete the connection
		defer func() {
			p.connections.Delete(connectionID)
		}()

		// Executor wraps a connection to have a safe abstraction
		p.Lock()
		e := executor.NewExecutor(safeConn, p.log, p.storage, connectionID, p.pubsubs)
		p.Unlock()

		p.log.Info("websocket client connected", "uuid", connectionID)

		err = e.StartCommandLoop()
		if err != nil {
			p.log.Error("command loop error", "error", err.Error())
			return
		}
	})
}

// Publish is an entry point to the websocket PUBSUB
func (p *Plugin) Publish(msg []pubsub.Message) error {
	p.Lock()
	defer p.Unlock()

	for i := 0; i < len(msg); i++ {
		for j := 0; j < len(msg[i].Topics()); j++ {
			if br, ok := p.pubsubs[msg[i].Broker()]; ok {
				err := br.Publish(msg)
				if err != nil {
					return errors.E(err)
				}
			} else {
				p.log.Warn("no such broker", "available", p.pubsubs, "requested", msg[i].Broker())
			}
		}
	}
	return nil
}

func (p *Plugin) PublishAsync(msg []pubsub.Message) {
	go func() {
		p.Lock()
		defer p.Unlock()
		for i := 0; i < len(msg); i++ {
			for j := 0; j < len(msg[i].Topics()); j++ {
				err := p.pubsubs[msg[i].Broker()].Publish(msg)
				if err != nil {
					p.log.Error("publish async error", "error", err)
					return
				}
			}
		}
	}()
}