5
5
"time"
6
6
7
7
sw "github.com/RussellLuo/slidingwindow"
8
+ "github.com/patrickmn/go-cache"
9
+ "github.com/samber/lo"
8
10
9
11
"github.com/flanksource/commons/collections"
10
12
"github.com/flanksource/config-db/api"
@@ -19,6 +21,8 @@ const (
19
21
ChangeTypeTooManyChanges = "TooManyChanges"
20
22
)
21
23
24
+ var configChangesCache = cache .New (time .Hour * 24 , time .Hour * 24 )
25
+
22
26
func GetWorkflowRunCount (ctx api.ScrapeContext , workflowID string ) (int64 , error ) {
23
27
var count int64
24
28
err := ctx .DB ().Table ("config_changes" ).
@@ -122,6 +126,7 @@ func syncCurrentlyRateLimitedConfigs(ctx api.ScrapeContext, window time.Duration
122
126
if err != nil {
123
127
return nil , err
124
128
}
129
+ defer rows .Close ()
125
130
126
131
output := make (map [string ]struct {})
127
132
for rows .Next () {
@@ -156,6 +161,7 @@ func syncWindow(ctx api.ScrapeContext, max int, window time.Duration) error {
156
161
if err != nil {
157
162
return err
158
163
}
164
+ defer rows .Close ()
159
165
160
166
for rows .Next () {
161
167
var configID string
@@ -179,3 +185,54 @@ func syncWindow(ctx api.ScrapeContext, max int, window time.Duration) error {
179
185
180
186
return rows .Err ()
181
187
}
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