-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(serverv2): remove unused interface methods, honuor context (#…
- Loading branch information
1 parent
470e085
commit c754b20
Showing
4 changed files
with
61 additions
and
27 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,22 @@ | ||
package api | ||
|
||
import "context" | ||
|
||
// DoUntilCtxExpired runs the given function until the context is expired or | ||
// the function exits. | ||
// This forces context to be honored. | ||
func DoUntilCtxExpired(ctx context.Context, f func()) error { | ||
done := make(chan struct{}) | ||
go func() { | ||
defer close(done) | ||
|
||
f() | ||
}() | ||
|
||
select { | ||
case <-ctx.Done(): | ||
return ctx.Err() | ||
case <-done: | ||
return nil | ||
} | ||
} |
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 @@ | ||
package api | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestDoUntilCtxExpired(t *testing.T) { | ||
t.Run("success", func(t *testing.T) { | ||
ctx := context.Background() | ||
|
||
funcRan := false | ||
err := DoUntilCtxExpired(ctx, func() { | ||
funcRan = true | ||
}) | ||
require.NoError(t, err) | ||
require.True(t, funcRan) | ||
}) | ||
|
||
t.Run("context expired", func(t *testing.T) { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
|
||
funcRan := false | ||
err := DoUntilCtxExpired(ctx, func() { | ||
cancel() | ||
funcRan = true | ||
<-time.After(time.Second) | ||
}) | ||
require.ErrorIs(t, err, context.Canceled) | ||
require.True(t, funcRan) | ||
}) | ||
} |