-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add DeliverLatest as common function for use by Manager and ProxyTrac…
…ker Open (#19564) Open add DeliverLatest as common function for use by Manager and ProxyTracker
- Loading branch information
Showing
3 changed files
with
46 additions
and
55 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
// Copyright (c) HashiCorp, Inc. | ||
// SPDX-License-Identifier: BUSL-1.1 | ||
package channels | ||
|
||
import "fmt" | ||
|
||
// DeliverLatest will drain the channel discarding any messages if there are any and sends the current message. | ||
func DeliverLatest[T any](val T, ch chan T) error { | ||
// Send if chan is empty | ||
select { | ||
case ch <- val: | ||
return nil | ||
default: | ||
} | ||
|
||
// If it falls through to here, the channel is not empty. | ||
// Drain the channel. | ||
done := false | ||
for !done { | ||
select { | ||
case <-ch: | ||
continue | ||
default: | ||
done = true | ||
} | ||
} | ||
|
||
// Attempt to send again. If it is not empty, throw an error | ||
select { | ||
case ch <- val: | ||
return nil | ||
default: | ||
return fmt.Errorf("failed to deliver latest event: chan full again after draining") | ||
} | ||
} |