forked from kubeshop/botkube-plugins-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (73 loc) · 1.83 KB
/
main.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
package main
import (
"context"
"fmt"
"time"
"github.com/hashicorp/go-plugin"
"github.com/kubeshop/botkube/pkg/api"
"github.com/kubeshop/botkube/pkg/api/source"
"gopkg.in/yaml.v3"
)
// version is set via ldflags by GoReleaser.
var version = "dev"
// Config holds the source configuration.
type Config struct {
Interval time.Duration
}
// Ticker implements the Botkube executor plugin interface.
type Ticker struct{}
// Metadata returns details about the Ticker plugin.
func (Ticker) Metadata(_ context.Context) (api.MetadataOutput, error) {
return api.MetadataOutput{
Version: version,
Description: "Emits an event at a specified interval",
}, nil
}
// Stream sends an event after configured time duration.
func (Ticker) Stream(ctx context.Context, in source.StreamInput) (source.StreamOutput, error) {
cfg, err := mergeConfigs(in.Configs)
if err != nil {
return source.StreamOutput{}, err
}
ticker := time.NewTicker(cfg.Interval)
out := source.StreamOutput{
Output: make(chan []byte),
}
go func() {
for {
select {
case <-ctx.Done():
ticker.Stop()
case <-ticker.C:
out.Output <- []byte("Ticker Event")
}
}
}()
return out, nil
}
func main() {
source.Serve(map[string]plugin.Plugin{
"ticker": &source.Plugin{
Source: &Ticker{},
},
})
}
// mergeConfigs merges all input configuration. In our case we don't have complex merge strategy,
// the last one that was specified wins :)
func mergeConfigs(configs []*source.Config) (Config, error) {
// default config
finalCfg := Config{
Interval: time.Minute,
}
for _, inputCfg := range configs {
var cfg Config
err := yaml.Unmarshal(inputCfg.RawYAML, &cfg)
if err != nil {
return Config{}, fmt.Errorf("while unmarshalling YAML config: %w", err)
}
if cfg.Interval != 0 {
finalCfg.Interval = cfg.Interval
}
}
return finalCfg, nil
}