-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
106 lines (90 loc) · 1.86 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package process
import (
"context"
"fmt"
"sync"
"time"
)
type errContextCanceled struct {
cause error
}
func (e *errContextCanceled) Error() string {
cause := "<nil>"
if e.cause != nil {
cause = e.cause.Error()
}
return fmt.Sprintf("context canceled: %s", cause)
}
func (e *errContextCanceled) Cause() error {
return e.cause
}
func (e *errContextCanceled) Unwrap() error {
return e.cause
}
type customContext struct {
parent context.Context
mu sync.Mutex
done chan struct{}
err error
}
type Context context.Context
type CancelFunc func(error)
// NewContext returns a new context with a custom error type
func NewContext() (Context, CancelFunc) {
return WithCancel(context.Background())
}
func WithCancel(ctx context.Context) (Context, CancelFunc) {
c := &customContext{
parent: ctx,
done: make(chan struct{}),
}
go c.propagateCancel()
return WithTrace(c), c.cancel
}
func (c *customContext) propagateCancel() {
select {
case <-c.parent.Done():
c.cancel(nil)
case <-c.done:
return
}
}
func (c *customContext) cancel(err error) {
c.mu.Lock()
defer c.mu.Unlock()
// prevent multiple cancels from panicking
select {
case <-c.done:
return
default:
}
// always give preference to the parent context
select {
case <-c.parent.Done():
c.err = c.parent.Err()
default:
c.err = WrapTrace(&errContextCanceled{cause: err})
}
close(c.done)
}
func (c *customContext) Done() <-chan struct{} {
return c.done
}
func (c *customContext) Err() error {
// if the parent is canceled, we are racing against propagateCancel so
// wait for it to complete
select {
case <-c.parent.Done():
<-c.done
default:
}
c.mu.Lock()
defer c.mu.Unlock()
return c.err
}
func (c *customContext) Value(key interface{}) interface{} {
return c.parent.Value(key)
}
func (c *customContext) Deadline() (deadline time.Time, ok bool) {
return c.parent.Deadline()
}