forked from dunglas/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
365 lines (294 loc) · 8.07 KB
/
hub.go
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Package mercure helps implement the Mercure protocol (https://mercure.rocks) in Go projects.
// It provides an implementation of a Mercure hub as an HTTP handler.
package mercure
import (
"errors"
"fmt"
"net/http"
"net/url"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/spf13/viper"
"go.uber.org/zap"
)
const (
DefaultWriteTimeout = 600 * time.Second
DefaultDispatchTimeout = 5 * time.Second
DefaultHeartbeat = 40 * time.Second
)
// ErrUnsupportedProtocolVersion is returned when the version passed is unsupported.
var ErrUnsupportedProtocolVersion = errors.New("compatibility mode only supports protocol version 7")
// Option instances allow to configure the library.
type Option func(h *opt) error
// WithAnonymous allows subscribers with no valid JWT.
func WithAnonymous() Option {
return func(o *opt) error {
o.anonymous = true
return nil
}
}
// WithDebug enables the debug mode.
func WithDebug() Option {
return func(o *opt) error {
o.debug = true
return nil
}
}
func WithUI() Option {
return func(o *opt) error {
o.ui = true
return nil
}
}
// WithDemo enables the demo.
func WithDemo() Option {
return func(o *opt) error {
o.demo = true
o.ui = true
return nil
}
}
// WithMetrics enables collection of Prometheus metrics.
func WithMetrics(m Metrics) Option {
return func(o *opt) error {
o.metrics = m
return nil
}
}
// WithSubscriptions allows to dispatch updates when subscriptions are created or terminated.
func WithSubscriptions() Option {
return func(o *opt) error {
o.subscriptions = true
return nil
}
}
// WithLogger sets the logger to use.
func WithLogger(logger Logger) Option {
return func(o *opt) error {
o.logger = logger
return nil
}
}
// WithWriteTimeout sets maximum duration before closing the connection, defaults to 600s, set to 0 to disable.
func WithWriteTimeout(timeout time.Duration) Option {
return func(o *opt) error {
o.writeTimeout = timeout
return nil
}
}
// WithDispatchTimeout sets maximum dispatch duration of an update.
func WithDispatchTimeout(timeout time.Duration) Option {
return func(o *opt) error {
o.dispatchTimeout = timeout
return nil
}
}
// WithHeartbeat sets the frequency of the heartbeat, disabled by default.
func WithHeartbeat(interval time.Duration) Option {
return func(o *opt) error {
o.heartbeat = interval
return nil
}
}
// WithPublisherJWTKeyFunc sets the function to use to parse and verify the publisher JWT.
func WithPublisherJWTKeyFunc(keyfunc jwt.Keyfunc) Option {
return func(o *opt) error {
o.publisherJWTKeyFunc = keyfunc
return nil
}
}
// WithSubscriberJWTKeyFunc sets the function to use to parse and verify the subscriber JWT.
func WithSubscriberJWTKeyFunc(keyfunc jwt.Keyfunc) Option {
return func(o *opt) error {
o.subscriberJWTKeyFunc = keyfunc
return nil
}
}
// WithPublisherJWT sets the JWT key and the signing algorithm to use for publishers.
func WithPublisherJWT(key []byte, alg string) Option {
return func(o *opt) error {
keyfunc, err := createJWTKeyfunc(key, alg)
o.publisherJWTKeyFunc = keyfunc
return err
}
}
// WithSubscriberJWT sets the JWT key and the signing algorithm to use for subscribers.
func WithSubscriberJWT(key []byte, alg string) Option {
return func(o *opt) error {
keyfunc, err := createJWTKeyfunc(key, alg)
o.subscriberJWTKeyFunc = keyfunc
return err
}
}
// WithAllowedHosts sets the allowed hosts.
func WithAllowedHosts(hosts []string) Option {
return func(o *opt) error {
o.allowedHosts = hosts
return nil
}
}
func validateOrigins(origins []string) error {
for _, origin := range origins {
switch origin {
case "*", "null":
continue
}
u, err := url.Parse(origin)
if err != nil ||
!u.IsAbs() ||
u.Opaque != "" ||
u.User != nil ||
u.Path != "" ||
u.RawQuery != "" ||
u.Fragment != "" {
return fmt.Errorf(`invalid origin, must be a URL having only a scheme, a host and optionally a port, "*" or "null": %w`, err)
}
}
return nil
}
// WithPublishOrigins sets the origins allowed to publish updates.
func WithPublishOrigins(origins []string) Option {
return func(o *opt) error {
if err := validateOrigins(origins); err != nil {
return err
}
o.publishOrigins = origins
return nil
}
}
// WithCORSOrigins sets the allowed CORS origins.
func WithCORSOrigins(origins []string) Option {
return func(o *opt) error {
if err := validateOrigins(origins); err != nil {
return err
}
o.corsOrigins = origins
return nil
}
}
// WithTransport sets the transport to use.
func WithTransport(t Transport) Option {
return func(o *opt) error {
o.transport = t
return nil
}
}
// WithTopicSelectorStore sets the TopicSelectorStore instance to use.
func WithTopicSelectorStore(tss *TopicSelectorStore) Option {
return func(o *opt) error {
o.topicSelectorStore = tss
return nil
}
}
// WithCookieName sets the name of the authorization cookie (defaults to "mercureAuthorization").
func WithCookieName(cookieName string) Option {
return func(o *opt) error {
o.cookieName = cookieName
return nil
}
}
// WithProtocolVersionCompatibility sets the version of the Mercure protocol to be backward compatible with (only version 7 is supported).
func WithProtocolVersionCompatibility(protocolVersionCompatibility int) Option {
return func(o *opt) error {
switch protocolVersionCompatibility {
case 7:
o.protocolVersionCompatibility = protocolVersionCompatibility
return nil
default:
return ErrUnsupportedProtocolVersion
}
}
}
// opt contains the available options.
//
// If you change this, also update the Caddy module and the documentation.
type opt struct {
transport Transport
topicSelectorStore *TopicSelectorStore
anonymous bool
debug bool
subscriptions bool
ui bool
demo bool
logger Logger
writeTimeout time.Duration
dispatchTimeout time.Duration
heartbeat time.Duration
publisherJWTKeyFunc jwt.Keyfunc
subscriberJWTKeyFunc jwt.Keyfunc
metrics Metrics
allowedHosts []string
publishOrigins []string
corsOrigins []string
cookieName string
protocolVersionCompatibility int
}
func (o *opt) isBackwardCompatiblyEnabledWith(version int) bool {
return o.protocolVersionCompatibility != 0 && version >= o.protocolVersionCompatibility
}
// Hub stores channels with clients currently subscribed and allows to dispatch updates.
type Hub struct {
*opt
handler http.Handler
// Deprecated: use the Caddy server module or the standalone library instead.
config *viper.Viper
server *http.Server
metricsServer *http.Server
}
// NewHub creates a new Hub instance.
func NewHub(options ...Option) (*Hub, error) {
opt := &opt{
writeTimeout: DefaultWriteTimeout,
dispatchTimeout: DefaultDispatchTimeout,
heartbeat: DefaultHeartbeat,
}
for _, o := range options {
if err := o(opt); err != nil {
return nil, err
}
}
if opt.logger == nil {
var (
l Logger
err error
)
if opt.debug {
l, err = zap.NewDevelopment()
} else {
l, err = zap.NewProduction()
}
if err != nil {
return nil, fmt.Errorf("error when creating logger: %w", err)
}
opt.logger = l
}
if opt.topicSelectorStore == nil {
tss, err := NewTopicSelectorStoreLRU(DefaultTopicSelectorStoreLRUMaxEntriesPerShard, DefaultTopicSelectorStoreLRUShardCount)
if err != nil {
return nil, err
}
opt.topicSelectorStore = tss
}
if opt.transport == nil {
opt.transport = NewLocalTransport()
}
if ttss, ok := opt.transport.(TransportTopicSelectorStore); ok {
ttss.SetTopicSelectorStore(opt.topicSelectorStore)
}
if opt.metrics == nil {
opt.metrics = NopMetrics{}
}
if opt.cookieName == "" {
opt.cookieName = defaultCookieName
}
h := &Hub{opt: opt}
h.initHandler()
return h, nil
}
// Stop stops the hub.
func (h *Hub) Stop() error {
if err := h.transport.Close(); err != nil {
return fmt.Errorf("transport error: %w", err)
}
return nil
}