github.com/argoproj/argo-events@v1.9.1/eventbus/kafka/sensor/trigger_conn.go (about) 1 package kafka 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "github.com/Knetic/govaluate" 9 "github.com/argoproj/argo-events/eventbus/common" 10 "github.com/argoproj/argo-events/eventbus/kafka/base" 11 cloudevents "github.com/cloudevents/sdk-go/v2" 12 ) 13 14 type KafkaTriggerConnection struct { 15 *base.KafkaConnection 16 KafkaTriggerHandler 17 18 sensorName string 19 triggerName string 20 depExpression *govaluate.EvaluableExpression 21 dependencies map[string]common.Dependency 22 atLeastOnce bool 23 24 // functions 25 close func() error 26 isClosed func() bool 27 transform func(string, cloudevents.Event) (*cloudevents.Event, error) 28 filter func(string, cloudevents.Event) bool 29 action func(map[string]cloudevents.Event) 30 31 // state 32 events []*eventWithMetadata 33 lastResetTime time.Time 34 } 35 36 type eventWithMetadata struct { 37 *cloudevents.Event 38 partition int32 39 offset int64 40 timestamp time.Time 41 } 42 43 func (e1 *eventWithMetadata) Same(e2 *eventWithMetadata) bool { 44 return e1.Source() == e2.Source() && e1.Subject() == e2.Subject() 45 } 46 47 func (e *eventWithMetadata) After(t time.Time) bool { 48 return t.IsZero() || e.timestamp.After(t) 49 } 50 51 func (c *KafkaTriggerConnection) String() string { 52 return fmt.Sprintf("KafkaTriggerConnection{Sensor:%s,Trigger:%s}", c.sensorName, c.triggerName) 53 } 54 55 func (c *KafkaTriggerConnection) Close() error { 56 if c.close == nil { 57 return fmt.Errorf("can't close Kafka trigger connection, close function is nil") 58 } 59 return c.close() 60 } 61 62 func (c *KafkaTriggerConnection) IsClosed() bool { 63 return c.isClosed == nil || c.isClosed() 64 } 65 66 func (c *KafkaTriggerConnection) Subscribe( 67 ctx context.Context, 68 closeCh <-chan struct{}, 69 resetConditionsCh <-chan struct{}, 70 lastResetTime time.Time, 71 transform func(depName string, event cloudevents.Event) (*cloudevents.Event, error), 72 filter func(string, cloudevents.Event) bool, 73 action func(map[string]cloudevents.Event), 74 topic *string) error { 75 c.transform = transform 76 c.filter = filter 77 c.action = action 78 c.lastResetTime = lastResetTime 79 80 for { 81 select { 82 case <-ctx.Done(): 83 return c.Close() 84 case <-closeCh: 85 // this is a noop since a kafka connection is maintained 86 // on the overall sensor vs indididual triggers 87 return nil 88 case <-resetConditionsCh: 89 // trigger update will filter out all events that occurred 90 // before this time 91 c.lastResetTime = time.Now() 92 } 93 } 94 }