/
event.go
114 lines (94 loc) · 2.25 KB
/
event.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
package events
import (
"fmt"
pb "github.com/talbright/keds/gen/proto"
"github.com/talbright/keds/plugin"
)
const (
InternalNamespace = "keds"
PluginNamespace = "plugin"
)
type Event struct {
*pb.PluginEvent
SourcePlugin *plugin.Plugin
}
type EventOption func(e *Event)
func NewEvent(event *pb.PluginEvent, src *plugin.Plugin) *Event {
e := &Event{SourcePlugin: src}
if event != nil {
e.PluginEvent = event
} else {
e.PluginEvent = &pb.PluginEvent{}
}
e.Args = make([]string, 0)
e.Data = make(map[string]string, 0)
if e.Source == "" && e.SourcePlugin != nil {
e.Source = e.SourcePlugin.GetName()
}
return e
}
func NewEventWithOptions(opts ...EventOption) *Event {
e := NewEvent(nil, nil)
e.ApplyOptions(opts...)
if e.Source == "" && e.SourcePlugin != nil {
e.Source = e.SourcePlugin.GetName()
}
return e
}
func (e *Event) ApplyOptions(opts ...EventOption) {
for _, option := range opts {
option(e)
}
}
func (e *Event) Proto() *pb.PluginEvent {
return e.PluginEvent
}
func CreateEventServerQuit(src *plugin.Plugin, exitCode int) (event *Event) {
return NewEventWithOptions(WithExitCode(exitCode), WithName("keds.exit"), WithSourcePlugin(src))
}
func CreateEventCommandInvoked(target *plugin.Plugin, args []string) (event *Event) {
return NewEventWithOptions(WithArgs(args), WithName("keds.command_invoked"), WithSource("keds"), WithTarget(target.GetName()))
}
func WithSourcePlugin(plug *plugin.Plugin) EventOption {
return func(e *Event) {
e.SourcePlugin = plug
}
}
func WithName(name string) EventOption {
return func(e *Event) {
e.Name = name
}
}
func WithTarget(target string) EventOption {
return func(e *Event) {
e.Target = target
}
}
func WithSource(source string) EventOption {
return func(e *Event) {
e.Source = source
}
}
func WithArgs(args []string) EventOption {
return func(e *Event) {
e.Args = args
}
}
func WithData(data map[string]string) EventOption {
return func(e *Event) {
e.Data = data
}
}
func WithExitCode(code int) EventOption {
return WithKeyPair("exit_code", fmt.Sprintf("%d", code))
}
func WithKeyPair(key string, val string) EventOption {
return func(e *Event) {
e.Data[key] = val
}
}
func WithArg(val string) EventOption {
return func(e *Event) {
e.Args = append(e.Args, val)
}
}