Skip to content

Commit 867aa63

Browse files
authored
fix: send more precise progress values (#304)
Include the running action progress in the actions progress calculation. The function now considers a failed action as completed, and is included in the progress. Not counting the failed action as completed might send some weird progress values e.g. [0%, 75%, (failed action occurs here) 50%], while if we count them, we should have [0%, 75%, 100%]. Related to hetznercloud/cli#528
1 parent f68e853 commit 867aa63

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

hcloud/action.go

+12-4
Original file line numberDiff line numberDiff line change
@@ -189,13 +189,14 @@ func (c *ActionClient) WatchOverallProgress(ctx context.Context, actions []*Acti
189189
defer close(errCh)
190190
defer close(progressCh)
191191

192-
successIDs := make([]int64, 0, len(actions))
192+
completedIDs := make([]int64, 0, len(actions))
193193
watchIDs := make(map[int64]struct{}, len(actions))
194194
for _, action := range actions {
195195
watchIDs[action.ID] = struct{}{}
196196
}
197197

198198
retries := 0
199+
previousProgress := 0
199200

200201
for {
201202
select {
@@ -224,20 +225,27 @@ func (c *ActionClient) WatchOverallProgress(ctx context.Context, actions []*Acti
224225
return
225226
}
226227

228+
progress := 0
227229
for _, a := range as {
228230
switch a.Status {
229231
case ActionStatusRunning:
230-
continue
232+
progress += a.Progress
231233
case ActionStatusSuccess:
232234
delete(watchIDs, a.ID)
233-
successIDs = append(successIDs, a.ID)
234-
sendProgress(progressCh, int(float64(len(actions)-len(successIDs))/float64(len(actions))*100))
235+
completedIDs = append(completedIDs, a.ID)
235236
case ActionStatusError:
236237
delete(watchIDs, a.ID)
238+
completedIDs = append(completedIDs, a.ID)
237239
errCh <- fmt.Errorf("action %d failed: %w", a.ID, a.Error())
238240
}
239241
}
240242

243+
progress += (len(completedIDs) * 100)
244+
if progress != 0 && progress != previousProgress {
245+
sendProgress(progressCh, int(progress/len(actions)))
246+
previousProgress = progress
247+
}
248+
241249
if len(watchIDs) == 0 {
242250
return
243251
}

hcloud/action_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ func TestActionClientWatchOverallProgress(t *testing.T) {
281281
t.Fatalf("expected hcloud.Error, but got: %#v", err)
282282
}
283283

284-
expectedProgressUpdates := []int{50}
284+
expectedProgressUpdates := []int{50, 100}
285285
if !reflect.DeepEqual(progressUpdates, expectedProgressUpdates) {
286286
t.Fatalf("expected progresses %v but received %v", expectedProgressUpdates, progressUpdates)
287287
}

0 commit comments

Comments
 (0)