-
Notifications
You must be signed in to change notification settings - Fork 3
/
handler.pubnub.go
482 lines (405 loc) · 12.5 KB
/
handler.pubnub.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// +build plugin_pubnub
package main
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
requ "plugins/request"
"sync/atomic"
"time"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
pngo "github.com/pubnub/go"
"github.com/rs/xid"
)
// pubnubPluginName is the PubNub plugin resgistered
// name that will be used in loging and plugin requests
const pubnubPluginName = "pubnub"
// init registers the built-in plugin to the global registery
func init() {
log.Println("[init] loading the PubNub plugin ...")
plugins[pubnubPluginName] = new(pubnubPlugin)
}
// pnServerName the name of server using this plugin
type pnServerName string
// pubnubPlugin is plugin related data
type pubnubPlugin struct {
isSetup bool
client struct {
conn map[string]*pngo.PubNub
channel map[string]string
}
config map[string]pubnubConfig
On map[string]func(string, string, interface{})
}
// pubnubConfig is the configuration options that
// can be set from within a ConfigHTTP block.
type pubnubConfig struct {
Name string `hcl:"name,label"`
PublishKey *hcl.Attribute `hcl:"publish_key"`
SubscribeKey *hcl.Attribute `hcl:"subscribe_key"`
Channel string `hcl:"channel,optional"`
UUID string `hcl:"uuid,optional"`
}
// pubnub stores confiurations that can come from
// the root block
type pubnub struct {
Name string `hcl:"name,label"`
Desc string `hcl:"_-,optional"`
SubscribeSocketIO []struct {
Namespace string `hcl:"ns,label"`
Event string `hcl:"event,label"`
Delay string `hcl:"delay,optional"`
Broadcast []pubnubBroadcast `hcl:"broadcast_socketio,block"`
Emit []pubnubEmit `hcl:"emit_socketio,block"`
} `hcl:"subscribe,block"`
PublishSocketIO []pubnubBroadcast `hcl:"broadcast_socketio,block"`
}
// pubnubBroadcast stores broadcast configurations
type pubnubBroadcast struct {
Namespace string `hcl:"ns,label"`
Event string `hcl:"event,label"`
Channel string `hcl:"channel,optional"`
Data *hcl.Attribute `hcl:"data"`
}
// pubnubEmit store emit configurations
type pubnubEmit struct {
Channel string `hcl:"channel,optional"`
Data *hcl.Attribute `hcl:"data"`
}
// Setup is a plugin construct for the inital
// setup of a plugin
func (p *pubnubPlugin) Setup() (err error) {
log.Println("[pubnub] setup plugin ...")
p.client.conn = make(map[string]*pngo.PubNub)
p.client.channel = make(map[string]string)
p.config = make(map[string]pubnubConfig)
p.On = make(map[string]func(string, string, interface{}))
return nil
}
// Version takes in the max version and returns the version
// that this module supports
func (p *pubnubPlugin) Version(int32) int32 { return 1 }
// Metadata returns the metadata of the plugin
func (p *pubnubPlugin) Metadata() string {
return `
metadata {
version = "0.1.0"
author = "Nika Jones"
copyright = "Nika Jones - © 2021"
}
`
}
// SetupConfig is a plugin construct for
// collecting service configuration information
// for setting up a plugin
func (p *pubnubPlugin) SetupConfig(svrName string, svrPlugins hcl.Body) (err error) {
cfg := p.config[svrName]
svrb, _, _ := svrPlugins.PartialContent(&hcl.BodySchema{
Blocks: []hcl.BlockHeaderSchema{
{
Type: pubnubPluginName,
LabelNames: []string{"name"},
},
},
})
if len(svrb.Blocks) == 0 {
return
}
for _, block := range svrb.Blocks {
var pnc pubnubConfig
switch block.Type {
case pubnubPluginName:
gohcl.DecodeBody(block.Body, nil, &pnc)
if len(block.Labels) > 0 {
pnc.Name = block.Labels[0] // the same index as the LabelNames above...
}
p.config[svrName] = pnc
cfg = p.config[svrName]
}
}
if cfg.UUID == "" {
cfg.UUID = xid.New().String()
p.config[svrName] = cfg
}
publishKey, dia := cfg.PublishKey.Expr.Value(&fileEvalCtx)
if dia.HasErrors() {
return dia
}
subscribeKey, dia := cfg.SubscribeKey.Expr.Value(&fileEvalCtx)
if dia.HasErrors() {
return dia
}
var conf = pngo.NewConfig()
conf.PublishKey = publishKey.AsString()
conf.SubscribeKey = subscribeKey.AsString()
conf.UUID = p.config[svrName].UUID
p.client.conn[cfg.Name] = pngo.NewPubNub(conf)
p.client.channel[cfg.Name] = cfg.Channel
log.Printf("[pubnub] client %s (channel: %q uuid: %q) ...", cfg.Name, cfg.Channel, cfg.UUID)
return nil
}
// SetupRoot is a plugin construct for collecting
// information from the root configuration and
// applying it during the setup phase
func (p *pubnubPlugin) SetupRoot(configPlugins hcl.Body) error {
var listener = p.NewListener()
cfgb, _, _ := configPlugins.PartialContent(&hcl.BodySchema{
Blocks: []hcl.BlockHeaderSchema{
{
Type: pubnubPluginName,
LabelNames: []string{"name"},
},
},
})
for _, block := range cfgb.Blocks {
var pn pubnub
switch block.Type {
case pubnubPluginName:
gohcl.DecodeBody(block.Body, nil, &pn)
if len(block.Labels) > 0 {
pn.Name = block.Labels[0] // the same index as the LabelNames above...
}
p.Subscribe(pn, listener)
}
}
return nil
}
// NewListener takes a root setup and starts a
// PubNub listener based on the config info. This
// is a channel that will collect all incoming
// requests from PubNub and pass it along to the
// proper config option for a response
func (p *pubnubPlugin) NewListener() *pngo.Listener {
log.Println("[pubnub] setup a listener ...")
var listener = pngo.NewListener()
go func() {
for {
select {
case message := <-listener.Message:
var uuid, ch, ns, event string
var data interface{}
if msg, ok := message.Message.(map[string]interface{}); ok {
ch = message.Channel
ns, _ = msg["ns"].(string)
event, _ = msg["name"].(string)
data, _ = msg["data"]
uuid, _ = msg["uuid"].(string)
}
log.Printf("[pubnub] message %s %s %s (%s) ...", ch, ns, event, uuid)
key := fmt.Sprintf("%s+%s+%s", ch, ns, event) // just smash together so we can have a unique event
if key == "++" {
continue
}
if _, ok := p.On[key]; ok {
log.Println("[pubnub] execute message callback ...")
if uuid == "" {
uuid = message.Publisher
}
p.On[key](uuid, ns, data)
}
}
}
}()
return listener
}
// Subscribe sends information back to the client and deteremines
// what will happen to the information that the listener passes back
// to it. Based on the configured information
func (p *pubnubPlugin) Subscribe(pn pubnub, listener *pngo.Listener) {
log.Printf("[pubnub] subcribe to %q ...", pn.Name)
conn, ok := p.client.conn[pn.Name]
if !ok {
return
}
for _, sio := range pn.SubscribeSocketIO {
name := p.client.channel[pn.Name]
log.Printf("[pubnub] SUB %q %q added ...", sio.Namespace, sio.Event)
conn.Subscribe().Channels([]string{name}).Execute()
p.client.conn[pn.Name].AddListener(listener)
// setup the callback
p.On[fmt.Sprintf("%s+%s+%s", name, sio.Namespace, sio.Event)] = func(sid, ns string, _ interface{}) {
log.Printf("[pubnub] callback message %s %s %s ...", name, sio.Namespace, sio.Event)
if len(sio.Emit) > 0 || len(sio.Broadcast) > 0 {
if len(sio.Delay) > 0 {
log.Printf("[pubnub] callback delay response for %s ...", sio.Delay)
time.Sleep(delay(sio.Delay))
}
}
for _, pub := range sio.Emit {
if pub.Data == nil {
continue
}
dataVal, dia := pub.Data.Expr.Value(&bodyEvalCtx)
if dia.HasErrors() {
for _, err := range dia.Errs() {
log.Printf("[pubnub] callback failed to emit: %v", err)
}
return
}
msg := map[string]interface{}{
"name": sid,
"ns": ns,
"data": toObject(dataVal.AsString()),
}
log.Println("[pubnub] callback emit ...")
_, status, err := conn.Publish().Channel(pub.Channel).Message(msg).Execute() // TODO(njones):look for errors
log.Printf("[pubnub] broadcast status: %d", status.StatusCode)
log.OnErr(err).Printf("[pubnub] error: %v", err)
}
for _, pub := range sio.Broadcast {
if pub.Data == nil {
continue
}
dataVal, dia := pub.Data.Expr.Value(&bodyEvalCtx)
if dia.HasErrors() {
for _, err := range dia.Errs() {
log.Printf("[pubnub] callback failed to broadcast: %v", err)
}
return
}
msg := map[string]interface{}{
"name": sid,
"ns": ns,
"data": toObject(dataVal.AsString()),
}
log.Println("[pubnub] callback broadcast ...")
conn.Publish().Channel(pub.Channel).Message(msg).Execute() // TODO(njones):look for errors
}
}
}
}
// PostMiddlewareHTTP is a plugin concept that will add the proper middleware to handle the request. This can
// be thought of as the final request. This is passed in all of the blocks, that can be used during setup
// then return a http.Handler that can be used during the request call.
func (p *pubnubPlugin) PostMiddlewareHTTP(path string, plugins hcl.Body, req requ.HTTP) (MiddlewareHTTP, bool) {
reqb, _, _ := plugins.PartialContent(&hcl.BodySchema{
Blocks: []hcl.BlockHeaderSchema{
{
Type: pubnubPluginName,
LabelNames: []string{"name"},
},
},
})
if len(reqb.Blocks) == 0 {
return nil, false
}
var reqPubNub []pubnub
for _, block := range reqb.Blocks {
var pn pubnub
switch block.Type {
case pubnubPluginName:
gohcl.DecodeBody(block.Body, nil, &pn)
if len(block.Labels) > 0 {
pn.Name = block.Labels[0]
}
reqPubNub = append(reqPubNub, pn)
}
}
if len(reqPubNub) == 0 {
return nil, false
}
var idx = int64(-1)
var resps = reqPubNub
if req.Order == "unordered" {
rand.Seed(time.Now().UnixNano()) // doesn't have to be crypto-quality random here...
}
log.Printf("[pubnub] %s http response added ...", path)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Print("[pubnub] starting http response ...")
defer func() { next.ServeHTTP(w, r) }()
log.Print("[pubnub] allow tick responses for 1m at most ...")
timeoutTimer := time.NewTimer(1 * time.Minute) // HARDCODED FOR NOW
timeout := timeoutTimer.C
go func() {