pre_go17.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build !go1.7
  5. // +build !go1.7
  6. package context
  7. import (
  8. "errors"
  9. "fmt"
  10. "sync"
  11. "time"
  12. )
  13. // An emptyCtx is never canceled, has no values, and has no deadline. It is not
  14. // struct{}, since vars of this type must have distinct addresses.
  15. type emptyCtx int
  16. func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
  17. return
  18. }
  19. func (*emptyCtx) Done() <-chan struct{} {
  20. return nil
  21. }
  22. func (*emptyCtx) Err() error {
  23. return nil
  24. }
  25. func (*emptyCtx) Value(key interface{}) interface{} {
  26. return nil
  27. }
  28. func (e *emptyCtx) String() string {
  29. switch e {
  30. case background:
  31. return "context.Background"
  32. case todo:
  33. return "context.TODO"
  34. }
  35. return "unknown empty Context"
  36. }
  37. var (
  38. background = new(emptyCtx)
  39. todo = new(emptyCtx)
  40. )
  41. // Canceled is the error returned by Context.Err when the context is canceled.
  42. var Canceled = errors.New("context canceled")
  43. // DeadlineExceeded is the error returned by Context.Err when the context's
  44. // deadline passes.
  45. var DeadlineExceeded = errors.New("context deadline exceeded")
  46. // WithCancel returns a copy of parent with a new Done channel. The returned
  47. // context's Done channel is closed when the returned cancel function is called
  48. // or when the parent context's Done channel is closed, whichever happens first.
  49. //
  50. // Canceling this context releases resources associated with it, so code should
  51. // call cancel as soon as the operations running in this Context complete.
  52. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  53. c := newCancelCtx(parent)
  54. propagateCancel(parent, c)
  55. return c, func() { c.cancel(true, Canceled) }
  56. }
  57. // newCancelCtx returns an initialized cancelCtx.
  58. func newCancelCtx(parent Context) *cancelCtx {
  59. return &cancelCtx{
  60. Context: parent,
  61. done: make(chan struct{}),
  62. }
  63. }
  64. // propagateCancel arranges for child to be canceled when parent is.
  65. func propagateCancel(parent Context, child canceler) {
  66. if parent.Done() == nil {
  67. return // parent is never canceled
  68. }
  69. if p, ok := parentCancelCtx(parent); ok {
  70. p.mu.Lock()
  71. if p.err != nil {
  72. // parent has already been canceled
  73. child.cancel(false, p.err)
  74. } else {
  75. if p.children == nil {
  76. p.children = make(map[canceler]bool)
  77. }
  78. p.children[child] = true
  79. }
  80. p.mu.Unlock()
  81. } else {
  82. go func() {
  83. select {
  84. case <-parent.Done():
  85. child.cancel(false, parent.Err())
  86. case <-child.Done():
  87. }
  88. }()
  89. }
  90. }
  91. // parentCancelCtx follows a chain of parent references until it finds a
  92. // *cancelCtx. This function understands how each of the concrete types in this
  93. // package represents its parent.
  94. func parentCancelCtx(parent Context) (*cancelCtx, bool) {
  95. for {
  96. switch c := parent.(type) {
  97. case *cancelCtx:
  98. return c, true
  99. case *timerCtx:
  100. return c.cancelCtx, true
  101. case *valueCtx:
  102. parent = c.Context
  103. default:
  104. return nil, false
  105. }
  106. }
  107. }
  108. // removeChild removes a context from its parent.
  109. func removeChild(parent Context, child canceler) {
  110. p, ok := parentCancelCtx(parent)
  111. if !ok {
  112. return
  113. }
  114. p.mu.Lock()
  115. if p.children != nil {
  116. delete(p.children, child)
  117. }
  118. p.mu.Unlock()
  119. }
  120. // A canceler is a context type that can be canceled directly. The
  121. // implementations are *cancelCtx and *timerCtx.
  122. type canceler interface {
  123. cancel(removeFromParent bool, err error)
  124. Done() <-chan struct{}
  125. }
  126. // A cancelCtx can be canceled. When canceled, it also cancels any children
  127. // that implement canceler.
  128. type cancelCtx struct {
  129. Context
  130. done chan struct{} // closed by the first cancel call.
  131. mu sync.Mutex
  132. children map[canceler]bool // set to nil by the first cancel call
  133. err error // set to non-nil by the first cancel call
  134. }
  135. func (c *cancelCtx) Done() <-chan struct{} {
  136. return c.done
  137. }
  138. func (c *cancelCtx) Err() error {
  139. c.mu.Lock()
  140. defer c.mu.Unlock()
  141. return c.err
  142. }
  143. func (c *cancelCtx) String() string {
  144. return fmt.Sprintf("%v.WithCancel", c.Context)
  145. }
  146. // cancel closes c.done, cancels each of c's children, and, if
  147. // removeFromParent is true, removes c from its parent's children.
  148. func (c *cancelCtx) cancel(removeFromParent bool, err error) {
  149. if err == nil {
  150. panic("context: internal error: missing cancel error")
  151. }
  152. c.mu.Lock()
  153. if c.err != nil {
  154. c.mu.Unlock()
  155. return // already canceled
  156. }
  157. c.err = err
  158. close(c.done)
  159. for child := range c.children {
  160. // NOTE: acquiring the child's lock while holding parent's lock.
  161. child.cancel(false, err)
  162. }
  163. c.children = nil
  164. c.mu.Unlock()
  165. if removeFromParent {
  166. removeChild(c.Context, c)
  167. }
  168. }
  169. // WithDeadline returns a copy of the parent context with the deadline adjusted
  170. // to be no later than d. If the parent's deadline is already earlier than d,
  171. // WithDeadline(parent, d) is semantically equivalent to parent. The returned
  172. // context's Done channel is closed when the deadline expires, when the returned
  173. // cancel function is called, or when the parent context's Done channel is
  174. // closed, whichever happens first.
  175. //
  176. // Canceling this context releases resources associated with it, so code should
  177. // call cancel as soon as the operations running in this Context complete.
  178. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
  179. if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
  180. // The current deadline is already sooner than the new one.
  181. return WithCancel(parent)
  182. }
  183. c := &timerCtx{
  184. cancelCtx: newCancelCtx(parent),
  185. deadline: deadline,
  186. }
  187. propagateCancel(parent, c)
  188. d := deadline.Sub(time.Now())
  189. if d <= 0 {
  190. c.cancel(true, DeadlineExceeded) // deadline has already passed
  191. return c, func() { c.cancel(true, Canceled) }
  192. }
  193. c.mu.Lock()
  194. defer c.mu.Unlock()
  195. if c.err == nil {
  196. c.timer = time.AfterFunc(d, func() {
  197. c.cancel(true, DeadlineExceeded)
  198. })
  199. }
  200. return c, func() { c.cancel(true, Canceled) }
  201. }
  202. // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
  203. // implement Done and Err. It implements cancel by stopping its timer then
  204. // delegating to cancelCtx.cancel.
  205. type timerCtx struct {
  206. *cancelCtx
  207. timer *time.Timer // Under cancelCtx.mu.
  208. deadline time.Time
  209. }
  210. func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
  211. return c.deadline, true
  212. }
  213. func (c *timerCtx) String() string {
  214. return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now()))
  215. }
  216. func (c *timerCtx) cancel(removeFromParent bool, err error) {
  217. c.cancelCtx.cancel(false, err)
  218. if removeFromParent {
  219. // Remove this timerCtx from its parent cancelCtx's children.
  220. removeChild(c.cancelCtx.Context, c)
  221. }
  222. c.mu.Lock()
  223. if c.timer != nil {
  224. c.timer.Stop()
  225. c.timer = nil
  226. }
  227. c.mu.Unlock()
  228. }
  229. // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  230. //
  231. // Canceling this context releases resources associated with it, so code should
  232. // call cancel as soon as the operations running in this Context complete:
  233. //
  234. // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  235. // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  236. // defer cancel() // releases resources if slowOperation completes before timeout elapses
  237. // return slowOperation(ctx)
  238. // }
  239. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  240. return WithDeadline(parent, time.Now().Add(timeout))
  241. }
  242. // WithValue returns a copy of parent in which the value associated with key is
  243. // val.
  244. //
  245. // Use context Values only for request-scoped data that transits processes and
  246. // APIs, not for passing optional parameters to functions.
  247. func WithValue(parent Context, key interface{}, val interface{}) Context {
  248. return &valueCtx{parent, key, val}
  249. }
  250. // A valueCtx carries a key-value pair. It implements Value for that key and
  251. // delegates all other calls to the embedded Context.
  252. type valueCtx struct {
  253. Context
  254. key, val interface{}
  255. }
  256. func (c *valueCtx) String() string {
  257. return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val)
  258. }
  259. func (c *valueCtx) Value(key interface{}) interface{} {
  260. if c.key == key {
  261. return c.val
  262. }
  263. return c.Context.Value(key)
  264. }