| 1 |
package ctxext |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
"time" |
| 6 |
|
| 7 |
context "golang.org/x/net/context" |
| 8 |
) |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 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 |
|
| 42 |
for _, c2 := range ctxts { |
| 43 |
go func(pctx context.Context) { |
| 44 |
select { |
| 45 |
case <-ctx.Done(): |
| 46 |
return |
| 47 |
case <-pctx.Done(): |
| 48 |
|
| 49 |
|
| 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 |
|
| 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) |
| 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 |
} |