55 "time"
66
77 sw "github.com/RussellLuo/slidingwindow"
8+ "github.com/patrickmn/go-cache"
9+ "github.com/samber/lo"
810
911 "github.com/flanksource/commons/collections"
1012 "github.com/flanksource/config-db/api"
@@ -19,6 +21,8 @@ const (
1921 ChangeTypeTooManyChanges = "TooManyChanges"
2022)
2123
24+ var configChangesCache = cache .New (time .Hour * 24 , time .Hour * 24 )
25+
2226func GetWorkflowRunCount (ctx api.ScrapeContext , workflowID string ) (int64 , error ) {
2327 var count int64
2428 err := ctx .DB ().Table ("config_changes" ).
@@ -122,6 +126,7 @@ func syncCurrentlyRateLimitedConfigs(ctx api.ScrapeContext, window time.Duration
122126 if err != nil {
123127 return nil , err
124128 }
129+ defer rows .Close ()
125130
126131 output := make (map [string ]struct {})
127132 for rows .Next () {
@@ -156,6 +161,7 @@ func syncWindow(ctx api.ScrapeContext, max int, window time.Duration) error {
156161 if err != nil {
157162 return err
158163 }
164+ defer rows .Close ()
159165
160166 for rows .Next () {
161167 var configID string
@@ -179,3 +185,54 @@ func syncWindow(ctx api.ScrapeContext, max int, window time.Duration) error {
179185
180186 return rows .Err ()
181187}
188+
189+ // filterOutPersistedChanges returns only those changes that weren't seen in the db.
190+ func filterOutPersistedChanges (ctx api.ScrapeContext , changes []* models.ConfigChange ) ([]* models.ConfigChange , error ) {
191+ // use cache to filter out ones that we've already seen before
192+ changes = lo .Filter (changes , func (c * models.ConfigChange , _ int ) bool {
193+ _ , found := configChangesCache .Get (c .ConfigID + c .ExternalChangeId )
194+ if found {
195+ _ = found
196+ }
197+ return ! found
198+ })
199+
200+ if len (changes ) == 0 {
201+ return nil , nil
202+ }
203+
204+ query := `SELECT config_id, external_change_id
205+ FROM config_changes
206+ WHERE (config_id, external_change_id) IN ?`
207+ args := lo .Map (changes , func (c * models.ConfigChange , _ int ) []string {
208+ return []string {c .ConfigID , c .ExternalChangeId }
209+ })
210+
211+ rows , err := ctx .DB ().Raw (query , args ).Rows ()
212+ if err != nil {
213+ return nil , err
214+ }
215+ defer rows .Close ()
216+
217+ existing := make (map [string ]struct {})
218+ for rows .Next () {
219+ var configID , externalChangeID string
220+ if err := rows .Scan (& configID , & externalChangeID ); err != nil {
221+ return nil , err
222+ }
223+
224+ configChangesCache .SetDefault (configID + externalChangeID , struct {}{})
225+ existing [configID + externalChangeID ] = struct {}{}
226+ }
227+
228+ newOnes := lo .Filter (changes , func (c * models.ConfigChange , _ int ) bool {
229+ _ , found := existing [c .ConfigID + c .ExternalChangeId ]
230+ return ! found
231+ })
232+
233+ if len (newOnes ) > 0 {
234+ _ = query
235+ }
236+
237+ return newOnes , nil
238+ }
0 commit comments