Skip to content

Commit 8afac62

Browse files
committed
use Batch helper for alerts / 1
1 parent 43bead3 commit 8afac62

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

pkg/database/alerts.go

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -160,32 +160,35 @@ func (c *Client) CreateOrUpdateAlert(ctx context.Context, machineID string, aler
160160
SetOrigin(*decisionItem.Origin).
161161
SetSimulated(*alertItem.Simulated).
162162
SetUUID(decisionItem.UUID)
163+
// XXX: can we attach the alert here and remove the second call to Batch() ?
164+
// SetOwnerID(foundAlert.ID)
163165

164166
decisionBuilders = append(decisionBuilders, decisionBuilder)
165167
}
166168

167-
decisions := []*ent.Decision{}
168-
169-
builderChunks := slicetools.Chunks(decisionBuilders, c.decisionBulkSize)
169+
// create missing decisions in batches
170170

171-
for _, builderChunk := range builderChunks {
172-
decisionsCreateRet, err := c.Ent.Decision.CreateBulk(builderChunk...).Save(ctx)
171+
decisions := make([]*ent.Decision, 0, len(decisionBuilders))
172+
if err := Batch(ctx, decisionBuilders, c.decisionBulkSize, func(ctx context.Context, b []*ent.DecisionCreate) error {
173+
ret, err := c.Ent.Decision.CreateBulk(b...).Save(ctx)
173174
if err != nil {
174-
return "", fmt.Errorf("creating alert decisions: %w", err)
175+
return fmt.Errorf("creating alert decisions: %w", err)
175176
}
176-
177-
decisions = append(decisions, decisionsCreateRet...)
177+
decisions = append(decisions, ret...)
178+
return nil
179+
}); err != nil {
180+
return "", err
178181
}
179182

180-
// now that we bulk created missing decisions, let's update the alert
181-
182-
decisionChunks := slicetools.Chunks(decisions, c.decisionBulkSize)
183+
// attach decisions to alert in batches
183184

184-
for _, decisionChunk := range decisionChunks {
185-
err = c.Ent.Alert.Update().Where(alert.UUID(alertItem.UUID)).AddDecisions(decisionChunk...).Exec(ctx)
186-
if err != nil {
187-
return "", fmt.Errorf("updating alert %s: %w", alertItem.UUID, err)
185+
if err := Batch(ctx, decisions, c.decisionBulkSize, func(ctx context.Context, d []*ent.Decision) error {
186+
if err := c.Ent.Alert.Update().Where(alert.UUID(alertItem.UUID)).AddDecisions(d...).Exec(ctx); err != nil {
187+
return fmt.Errorf("updating alert %s: %w", alertItem.UUID, err)
188188
}
189+
return nil
190+
}); err != nil {
191+
return "", err
189192
}
190193

191194
return "", nil

0 commit comments

Comments
 (0)