/
trigger_conn.go
94 lines (80 loc) · 2.3 KB
/
trigger_conn.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
package kafka
import (
"context"
"fmt"
"time"
"github.com/Knetic/govaluate"
"github.com/argoproj/argo-events/eventbus/common"
"github.com/argoproj/argo-events/eventbus/kafka/base"
cloudevents "github.com/cloudevents/sdk-go/v2"
)
type KafkaTriggerConnection struct {
*base.KafkaConnection
KafkaTriggerHandler
sensorName string
triggerName string
depExpression *govaluate.EvaluableExpression
dependencies map[string]common.Dependency
atLeastOnce bool
// functions
close func() error
isClosed func() bool
transform func(string, cloudevents.Event) (*cloudevents.Event, error)
filter func(string, cloudevents.Event) bool
action func(map[string]cloudevents.Event)
// state
events []*eventWithMetadata
lastResetTime time.Time
}
type eventWithMetadata struct {
*cloudevents.Event
partition int32
offset int64
timestamp time.Time
}
func (e1 *eventWithMetadata) Same(e2 *eventWithMetadata) bool {
return e1.Source() == e2.Source() && e1.Subject() == e2.Subject()
}
func (e *eventWithMetadata) After(t time.Time) bool {
return t.IsZero() || e.timestamp.After(t)
}
func (c *KafkaTriggerConnection) String() string {
return fmt.Sprintf("KafkaTriggerConnection{Sensor:%s,Trigger:%s}", c.sensorName, c.triggerName)
}
func (c *KafkaTriggerConnection) Close() error {
if c.close == nil {
return fmt.Errorf("can't close Kafka trigger connection, close function is nil")
}
return c.close()
}
func (c *KafkaTriggerConnection) IsClosed() bool {
return c.isClosed == nil || c.isClosed()
}
func (c *KafkaTriggerConnection) Subscribe(
ctx context.Context,
closeCh <-chan struct{},
resetConditionsCh <-chan struct{},
lastResetTime time.Time,
transform func(depName string, event cloudevents.Event) (*cloudevents.Event, error),
filter func(string, cloudevents.Event) bool,
action func(map[string]cloudevents.Event),
topic *string) error {
c.transform = transform
c.filter = filter
c.action = action
c.lastResetTime = lastResetTime
for {
select {
case <-ctx.Done():
return c.Close()
case <-closeCh:
// this is a noop since a kafka connection is maintained
// on the overall sensor vs indididual triggers
return nil
case <-resetConditionsCh:
// trigger update will filter out all events that occurred
// before this time
c.lastResetTime = time.Now()
}
}
}