Skip to content

Commit 8f72a8c

Browse files
authored
Merge pull request #1220 from ydb-platform/xcontext
added `xcontext.WithDone()` + replaced custom implementation `xcontext.ValueOnly()` to standard `context.WithoutCancel()`
2 parents 7842cf9 + 20e9fde commit 8f72a8c

File tree

3 files changed

+71
-12
lines changed

3 files changed

+71
-12
lines changed

internal/xcontext/done.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package xcontext
2+
3+
import (
4+
"context"
5+
"time"
6+
)
7+
8+
type doneCtx <-chan struct{}
9+
10+
func (done doneCtx) Deadline() (deadline time.Time, ok bool) {
11+
return
12+
}
13+
14+
func (done doneCtx) Done() <-chan struct{} {
15+
return done
16+
}
17+
18+
func (done doneCtx) Err() error {
19+
select {
20+
case <-done:
21+
return context.Canceled
22+
default:
23+
return nil
24+
}
25+
}
26+
27+
func (done doneCtx) Value(key any) any {
28+
return nil
29+
}
30+
31+
func WithDone(parent context.Context, done <-chan struct{}) (context.Context, context.CancelFunc) {
32+
ctx, cancel := context.WithCancel(parent)
33+
stop := context.AfterFunc(doneCtx(done), func() {
34+
cancel()
35+
})
36+
37+
return ctx, func() {
38+
stop()
39+
cancel()
40+
}
41+
}

internal/xcontext/done_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package xcontext
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func TestWithDone(t *testing.T) {
11+
t.Run("CancelParent", func(t *testing.T) {
12+
ctx, cancel := context.WithCancel(context.Background())
13+
done := make(chan struct{})
14+
ctx1, _ := WithDone(ctx, done)
15+
require.NoError(t, ctx1.Err())
16+
cancel()
17+
require.Error(t, ctx1.Err())
18+
})
19+
t.Run("CloseDone", func(t *testing.T) {
20+
ctx, cancel := context.WithCancel(context.Background())
21+
defer cancel()
22+
done := make(chan struct{})
23+
ctx1, cancel1 := WithDone(ctx, done)
24+
require.NoError(t, ctx1.Err())
25+
cancel1()
26+
require.NoError(t, ctx.Err())
27+
require.Error(t, ctx1.Err())
28+
})
29+
}

internal/xcontext/without_deadline.go

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,9 @@ package xcontext
22

33
import (
44
"context"
5-
"time"
65
)
76

8-
type valueOnlyContext struct {
9-
context.Context //nolint:containedctx
10-
}
11-
12-
func (valueOnlyContext) Deadline() (deadline time.Time, ok bool) { return }
13-
14-
func (valueOnlyContext) Done() <-chan struct{} { return nil }
15-
16-
func (valueOnlyContext) Err() error { return nil }
17-
187
// ValueOnly helps to clear parent context from deadlines/cancels
198
func ValueOnly(ctx context.Context) context.Context {
20-
return valueOnlyContext{ctx}
9+
return context.WithoutCancel(ctx)
2110
}

0 commit comments

Comments
 (0)