-
Notifications
You must be signed in to change notification settings - Fork 53
/
watcher.go
64 lines (54 loc) · 1.35 KB
/
watcher.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
package management
import (
"context"
"github.com/samber/lo"
"google.golang.org/protobuf/proto"
)
type ConditionWatcher interface {
WatchEvents()
}
type internalWatcher struct {
closures []func()
}
func NewConditionWatcher(cl ...func()) ConditionWatcher {
return &internalWatcher{
closures: cl,
}
}
func (w *internalWatcher) WatchEvents() {
for _, cl := range w.closures {
cl := cl
go func() {
cl()
}()
}
}
type WatcherHooks[T any] interface {
RegisterEvent(eventType func(T) bool, hooks ...func(context.Context, T) error)
HandleEvent(T)
}
type ManagementWatcherHooks[T proto.Message] struct {
parentCtx context.Context
hooks []lo.Tuple2[func(T) bool, []func(context.Context, T) error]
}
func NewManagementWatcherHooks[T proto.Message](ctx context.Context) *ManagementWatcherHooks[T] {
return &ManagementWatcherHooks[T]{
parentCtx: ctx,
hooks: make([]lo.Tuple2[func(T) bool, []func(context.Context, T) error], 0),
}
}
func (h *ManagementWatcherHooks[T]) RegisterHook(filter func(T) bool, hooks ...func(context.Context, T) error) {
h.hooks = append(h.hooks, lo.Tuple2[func(T) bool, []func(context.Context, T) error]{
A: filter,
B: hooks,
})
}
func (h *ManagementWatcherHooks[T]) HandleEvent(event T) {
for _, cs := range h.hooks {
if cs.A(event) {
for _, hook := range cs.B {
hook(h.parentCtx, event)
}
}
}
}