Skip to content

Commit dc727be

Browse files
committed
retain the original order of the last updates for each key
Signed-off-by: Huabing Zhao <[email protected]>
1 parent 53caaa1 commit dc727be

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

internal/message/watchutil.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -117,20 +117,22 @@ func coalesceUpdates[K comparable, V any](runner string, updates []watchable.Upd
117117
result := make([]watchable.Update[K, V], 0, len(updates))
118118
indexByKey := make(map[K]int, len(updates))
119119

120-
for _, update := range updates {
121-
if idx, ok := indexByKey[update.Key]; ok {
122-
// Keep the latest update for this key.
123-
result[idx] = update
120+
for i := len(updates) - 1; i >= 0; i-- {
121+
update := updates[i]
122+
if _, ok := indexByKey[update.Key]; ok {
124123
continue
125124
}
126125

127126
indexByKey[update.Key] = len(result)
128127
result = append(result, update)
129128
}
130129

131-
if len(result) != len(updates) {
132-
logger.WithValues("runner", runner).Info("coalesced updates", "count", len(result), "before", len(updates))
130+
// Reverse the result slice to restore the original order of the last updates for each key
131+
for left, right := 0, len(result)-1; left < right; left, right = left+1, right-1 {
132+
result[left], result[right] = result[right], result[left]
133133
}
134134

135+
logger.WithValues("runner", runner).Info("coalesced updates", "count", len(result), "before", len(updates))
136+
135137
return result
136138
}

internal/message/watchutil_internal_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@ func TestCoalesceUpdates(t *testing.T) {
5151
},
5252
expected: []watchable.Update[string, int]{
5353
{Key: "foo", Value: 5},
54-
{Key: "bar", Value: 7},
5554
{Key: "baz", Delete: true, Value: 6},
55+
{Key: "bar", Value: 7},
5656
},
5757
},
5858
}

0 commit comments

Comments
 (0)