Debian Codegraph @

dag/dagctx.go

raw symbols SCIP
1 package ctxext
2
3 import (
4 "sync"
5 "time"
6
7 context "golang.org/x/net/context"
8 )
9
10 // WithParents returns a Context that listens to all given
11 // parents. It effectively transforms the Context Tree into
12 // a Directed Acyclic Graph. This is useful when a context
13 // may be cancelled for more than one reason. For example,
14 // consider a database with the following Get function:
15 //
16 // func (db *DB) Get(ctx context.Context, ...) {}
17 //
18 // DB.Get may have to stop for two different contexts:
19 // * the caller's context (caller might cancel)
20 // * the database's context (might be shut down mid-request)
21 //
22 // WithParents saves the day by allowing us to "merge" contexts
23 // and continue on our merry contextual way:
24 //
25 // ctx = ctxext.WithParents(ctx, db.ctx)
26 //
27 // Passing related (mutually derived) contexts to WithParents is
28 // actually ok. The child is cancelled when any of its parents is
29 // cancelled, so if any of its parents are also related, the cancel
30 // propagation will reach the child via the shortest path.
31 func WithParents(ctxts ...context.Context) context.Context {
32 if len(ctxts) < 1 {
33 panic("no contexts provided")
34 }
35
36 ctx := &errCtx{
37 done: make(chan struct{}),
38 dead: earliestDeadline(ctxts),
39 }
40
41 // listen to all contexts and use the first.
42 for _, c2 := range ctxts {
43 go func(pctx context.Context) {
44 select {
45 case <-ctx.Done(): // cancelled by another parent
46 return
47 case <-pctx.Done(): // this parent cancelled
48 // race: two parents may have cancelled at the same time.
49 // break tie with mutex (inside c.cancel)
50 ctx.cancel(pctx.Err())
51 }
52 }(c2)
53 }
54
55 return ctx
56 }
57
58 func earliestDeadline(ctxts []context.Context) *time.Time {
59 var d1 *time.Time
60 for _, c := range ctxts {
61 if c == nil {
62 panic("given nil context.Context")
63 }
64
65 // use earliest deadline.
66 d2, ok := c.Deadline()
67 if !ok {
68 continue
69 }
70
71 if d1 == nil || (*d1).After(d2) {
72 d1 = &d2
73 }
74 }
75 return d1
76 }
77
78 type errCtx struct {
79 dead *time.Time
80 done chan struct{}
81 err error
82 mu sync.RWMutex
83 }
84
85 func (c *errCtx) cancel(err error) {
86 c.mu.Lock()
87 defer c.mu.Unlock()
88
89 select {
90 case <-c.Done():
91 return
92 default:
93 }
94
95 c.err = err
96 close(c.done) // signal done to all
97 }
98
99 func (c *errCtx) Done() <-chan struct{} {
100 return c.done
101 }
102
103 func (c *errCtx) Err() error {
104 c.mu.Lock()
105 defer c.mu.Unlock()
106 return c.err
107 }
108
109 func (c *errCtx) Value(key interface{}) interface{} {
110 return nil
111 }
112
113 func (c *errCtx) Deadline() (deadline time.Time, ok bool) {
114 if c.dead == nil {
115 return
116 }
117
118 return *c.dead, true
119 }