This repository was archived by the owner on Jan 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.go
More file actions
472 lines (375 loc) · 9.56 KB
/
plugin.go
File metadata and controls
472 lines (375 loc) · 9.56 KB
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
package plugins
import (
"context"
"sync"
"github.com/andersnormal/autobot/pkg/plugins/filters"
"github.com/andersnormal/autobot/pkg/plugins/message"
"github.com/andersnormal/autobot/pkg/plugins/runtime"
pb "github.com/andersnormal/autobot/proto"
"github.com/nats-io/nats.go"
"github.com/nats-io/stan.go"
log "github.com/sirupsen/logrus"
)
// Event symbolizes events that can occur in the plugin.
// Though they maybe triggered from somewhere else.
type Event interface{}
const (
// ErrUnknown ...
ErrUnknown = iota
// ErrParse ...
ErrParse
)
// MessageError represents an error that may occurs
type MessageError struct {
Code int
Msg string
}
// returns
func (e MessageError) Error() string {
return e.Msg
}
// Plugin describes a plugin in general.
// It should not be instantiated directly.
type Plugin struct {
opts *Opts
sc stan.Conn
nc *nats.Conn
marshaler message.Marshaler
runtime *runtime.Environment
ctx context.Context
cancel func()
errOnce sync.Once
err error
wg sync.WaitGroup
logger *log.Entry
sync.RWMutex
}
// Opt is an Option
type Opt func(*Opts)
// Opts are the available options
type Opts struct{}
// SubscribeFunc ...
type SubscribeFunc = func(Context) error
// WithContext is creating a new plugin and a context to run operations in routines.
// When the context is canceled, all concurrent operations are canceled.
func WithContext(ctx context.Context, env *runtime.Environment, opts ...Opt) (*Plugin, context.Context) {
p := newPlugin(env, opts...)
ctx, cancel := context.WithCancel(ctx)
p.cancel = cancel
p.ctx = ctx
return p, ctx
}
// Log is returning the logger to log to the log formatter.
func (p *Plugin) Log() *log.Entry {
return p.logger
}
// newPlugin ...
func newPlugin(env *runtime.Environment, opts ...Opt) *Plugin {
options := new(Opts)
p := new(Plugin)
// setting a default env for a plugin
p.opts = options
p.runtime = env
// this is the basic marshaler
p.marshaler = message.JSONMarshaler{NewUUID: message.NewUUID}
// configure plugin
_ = configure(p, opts...)
// logging ...
_ = configureLogging(p)
return p
}
// SubscribeInbox is subscribing to the inbox of messages.
// This if for plugins that want to consume the message that other
// plugins publish to Autobot.
func (p *Plugin) SubscribeInbox(funcs ...filters.FilterFunc) <-chan Event {
sub := make(chan Event)
p.run(p.subInboxFunc(sub, funcs...))
return sub
}
// SubscribeOutbox is subscribing to the outbox of messages.
// These are the message that ought to be published to an external service (e.g. Slack, MS Teams).
func (p *Plugin) SubscribeOutbox(funcs ...filters.FilterFunc) <-chan Event {
sub := make(chan Event)
p.run(p.subOutboxFunc(sub, funcs...))
return sub
}
// PublishInbox is publishing message to the inbox in the controller.
func (p *Plugin) PublishInbox(msg *pb.Message) error { // male this an actual interface
return p.publish(p.runtime.Inbox, msg)
}
// PublishOutbox is publishing message to the outbox in the controller.
func (p *Plugin) PublishOutbox(msg *pb.Message) error {
return p.publish(p.runtime.Outbox, msg)
}
// Wait is waiting for the underlying WaitGroup. All run go routines are
// hold here to before one exists with an error. Then the provided context is canceled.
func (p *Plugin) Wait() error {
p.wg.Wait()
if p.sc != nil {
p.sc.Close()
}
if p.nc != nil {
p.nc.Close()
}
return p.err
}
// AsyncReplyWithFunc is a wrapper function to provide a message handler function
// which will asynchronously reply to the messages received by a plugin.
// The difference between this and the synchronous ReplyWithFunc wrapper is that
// while both receive messages in sequence, ReplyWithFunc will block on reading
// the subsequent message from the inbox while the current message is being handled.
func (p *Plugin) AsyncReplyWithFunc(fn SubscribeFunc, funcs ...filters.FilterFunc) error {
p.run(func() error {
subMsg := p.SubscribeInbox()
for {
select {
case e, ok := <-subMsg:
if !ok {
return nil
}
switch ev := e.(type) {
case *MessageError:
return ev
case *pb.Message:
// creating a new context for the message
// this could be moved to a sync.Pool
ctx := &cbContext{
plugin: p,
msg: ev,
}
// launch goroutine to handle async reply handling
p.asyncHandleMessage(ctx, fn)
default:
}
case <-p.ctx.Done():
return nil
}
}
})
return nil
}
// asyncHandleMessage is a helper used to
func (p *Plugin) asyncHandleMessage(c Context, fn SubscribeFunc) {
p.run(func() error {
err := fn(c)
// TODO: in 1.1 we will enqueue to a dead letter topic and proceed
// perhaps, unless a specific error is returned.
return err
})
}
// ReplyWithFunc is a wrapper function to provide a function which may
// send replies to received message for this plugin.
func (p *Plugin) ReplyWithFunc(fn SubscribeFunc, funcs ...filters.FilterFunc) error {
p.run(func() error {
subMsg := p.SubscribeInbox()
for {
select {
case e, ok := <-subMsg:
if !ok {
return nil
}
switch ev := e.(type) {
case *MessageError:
return ev
case *pb.Message:
// creating a new context for the message
// this could be moved to a sync.Pool
ctx := &cbContext{
plugin: p,
msg: ev,
}
err := fn(ctx)
if err != nil {
return err
}
default:
}
case <-p.ctx.Done():
return nil
}
}
})
return nil
}
func (p *Plugin) run(f func() error) {
p.wg.Add(1)
go func() {
defer p.wg.Done()
if err := f(); err != nil {
p.errOnce.Do(func() {
p.err = err
if p.cancel != nil {
p.cancel()
}
})
}
}()
}
func (p *Plugin) getConn() (stan.Conn, error) {
p.Lock()
defer p.Unlock()
if p.sc != nil {
return p.sc, nil
}
c, err := p.newConn()
if err != nil {
return nil, err
}
p.sc = c
// start watcher ...
p.run(p.watchcat())
return p.sc, nil
}
func (p *Plugin) newConn() (stan.Conn, error) {
nc, err := nats.Connect(
p.runtime.ClusterURL,
nats.MaxReconnects(-1),
nats.ReconnectBufSize(-1),
)
if err != nil {
return nil, err
}
p.nc = nc
sc, err := stan.Connect(
p.runtime.ClusterID,
p.runtime.Name,
stan.NatsConn(nc),
stan.SetConnectionLostHandler(p.lostHandler()),
)
if err != nil {
return nil, err
}
return sc, nil
}
func (p *Plugin) watchcat() func() error {
return func() error {
<-p.ctx.Done()
if p.sc != nil {
// defer to make sure subscribers have a chance
// to unsubcribe cleanly.
defer p.sc.Close()
}
if p.nc != nil {
defer p.nc.Close()
}
return nil
}
}
func (p *Plugin) publish(topic string, msg *pb.Message) error {
sc, err := p.getConn()
if err != nil {
return err
}
b, err := p.marshaler.Marshal(msg)
if err != nil {
return err
}
if err := sc.Publish(topic, b); err != nil {
return err
}
return nil
}
func (p *Plugin) subInboxFunc(sub chan<- Event, funcs ...filters.FilterFunc) func() error {
return func() error {
sc, err := p.getConn()
if err != nil {
return err
}
f := filters.New(funcs...)
// we are using a queue subscription to only deliver the work to one of the plugins,
// because they subscribe to a group by the plugin name.
s, err := sc.QueueSubscribe(p.runtime.Inbox, p.runtime.Name, func(m *stan.Msg) {
botMessage := new(pb.Message)
if err := p.marshaler.Unmarshal(m.Data, botMessage); err != nil {
sub <- &MessageError{Code: ErrParse, Msg: err.Error()}
return
}
// filtering an event
event, err := f.Filter(botMessage)
if err != nil {
sub <- &MessageError{Code: ErrParse, Msg: err.Error()}
return
}
// if this has not been filtered, or else
if event != nil {
sub <- event
}
}, stan.DurableName(p.runtime.Name), stan.DeliverAllAvailable())
if err != nil {
return err
}
<-p.ctx.Done()
s.Close()
// close channel
close(sub)
sub = nil
return nil
}
}
func (p *Plugin) subOutboxFunc(sub chan<- Event, funcs ...filters.FilterFunc) func() error {
return func() error {
sc, err := p.getConn()
if err != nil {
return err
}
f := filters.New(funcs...)
// we are using a queue subscription to only deliver the work to one of the plugins,
// because they subscribe to a group by the plugin name.
s, err := sc.QueueSubscribe(p.runtime.Outbox, p.runtime.Name, func(m *stan.Msg) {
botMessage := new(pb.Message)
if err := p.marshaler.Unmarshal(m.Data, botMessage); err != nil {
sub <- &MessageError{Code: ErrParse, Msg: err.Error()}
return
}
// filtering an event
event, err := f.Filter(botMessage)
if err != nil {
sub <- &MessageError{Code: ErrParse, Msg: err.Error()}
return
}
// if this has not been filtered, or else
if event != nil {
sub <- event
}
}, stan.DurableName(p.runtime.Name), stan.DeliverAllAvailable())
if err != nil {
return err
}
<-p.ctx.Done()
s.Close()
// close channel
close(sub)
sub = nil
return nil
}
}
func (p *Plugin) lostHandler() func(_ stan.Conn, reason error) {
return func(_ stan.Conn, reason error) {
p.cancel()
p.err = reason
}
}
func configureLogging(p *Plugin) error {
log.SetFormatter(&log.TextFormatter{})
log.SetLevel(log.InfoLevel)
if p.runtime.LogFormat == "json" {
log.SetFormatter(&log.JSONFormatter{})
}
p.logger = log.WithFields(
log.Fields{
"autobot_name": p.runtime.Name,
"cluster_url": p.runtime.ClusterURL,
"cluster_id": p.runtime.ClusterID,
},
)
if level, err := log.ParseLevel(p.runtime.LogLevel); err == nil {
log.SetLevel(level)
}
return nil
}
func configure(p *Plugin, opts ...Opt) error {
for _, o := range opts {
o(p.opts)
}
return nil
}