context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. // Package context defines the Context type, which carries deadlines, cancellation
  5. // signals, and other request-scoped values across API boundaries and between
  6. // processes.
  7. //
  8. // Incoming requests to a server establish a Context, and outgoing calls to servers
  9. // should accept a Context. The chain of function calls between must propagate the
  10. // Context, optionally replacing it with a modified copy created using
  11. // WithDeadline, WithTimeout, WithCancel, or WithValue.
  12. //
  13. // Programs that use Contexts should follow these rules to keep interfaces
  14. // consistent across packages and enable static analysis tools to check context
  15. // propagation:
  16. //
  17. // Do not store Contexts inside a struct type; instead, pass a Context
  18. // explicitly to each function that needs it. The Context should be the first
  19. // parameter, typically named ctx:
  20. //
  21. // func DoSomething(ctx context.Context, arg Arg) error {
  22. // // ... use ctx ...
  23. // }
  24. //
  25. // Do not pass a nil Context, even if a function permits it. Pass context.TODO
  26. // if you are unsure about which Context to use.
  27. //
  28. // Use context Values only for request-scoped data that transits processes and
  29. // APIs, not for passing optional parameters to functions.
  30. //
  31. // The same Context may be passed to functions running in different goroutines;
  32. // Contexts are safe for simultaneous use by multiple goroutines.
  33. package context
  34. import (
  35. "errors"
  36. "sync"
  37. "time"
  38. )
  39. // A Context carries deadlines, and cancellation signals, and other values
  40. // across API boundaries.
  41. //
  42. // Context's methods may be called by multiple goroutines simultaneously.
  43. type Context interface {
  44. // Deadline returns the time when work done on behalf of this context
  45. // should be canceled. Deadline returns ok==false when no deadline is
  46. // set. Successive calls to Deadline return the same results.
  47. Deadline() (deadline time.Time, ok bool)
  48. // Done returns a channel that's closed when work done on behalf of this
  49. // context should be canceled. Done may return nil if this context can
  50. // never become done. Successive calls to Done return the same value.
  51. //
  52. // WithCancel arranges for Done to be closed when cancel is called;
  53. // WithDeadline arranges for Done to be closed when the deadline
  54. // expires; WithTimeout arranges for Done to be closed when the timeout
  55. // elapses.
  56. //
  57. // Done is provided for use in select statements:
  58. //
  59. // // DoSomething calls DoSomethingSlow and returns as soon as
  60. // // it returns or ctx.Done is closed.
  61. // func DoSomething(ctx context.Context) (Result, error) {
  62. // c := make(chan Result, 1)
  63. // go func() { c <- DoSomethingSlow(ctx) }()
  64. // select {
  65. // case res := <-c:
  66. // return res, nil
  67. // case <-ctx.Done():
  68. // return nil, ctx.Err()
  69. // }
  70. // }
  71. Done() <-chan struct{}
  72. // Err returns a non-nil error value after Done is closed. Err returns
  73. // Canceled if the context was canceled; Err returns DeadlineExceeded if
  74. // the context's deadline passed. No other values for Err are defined.
  75. // After Done is closed, successive calls to Err return the same value.
  76. Err() error
  77. // Value returns the value associated with this context for key, or nil
  78. // if no value is associated with key. Successive calls to Value with
  79. // the same key returns the same result.
  80. //
  81. // Use context values only for request-scoped data that transits
  82. // processes and APIs, not for passing optional parameters to functions.
  83. //
  84. // A key identifies a specific value in a Context. Functions that wish
  85. // to store values in Context typically allocate a key in a global
  86. // variable then use that key as the argument to context.WithValue and
  87. // Context.Value. A key can be any type that supports equality;
  88. // packages should define keys as an unexported type to avoid
  89. // collisions.
  90. //
  91. // Packages that define a Context key should provide type-safe accessors
  92. // for the values stores using that key:
  93. //
  94. // // Package user defines a User type that's stored in Contexts.
  95. // package user
  96. //
  97. // import "code.google.com/p/go.net/context"
  98. //
  99. // // User is the type of value stored in the Contexts.
  100. // type User struct {...}
  101. //
  102. // // key is an unexported type for keys defined in this package.
  103. // // This prevents collisions with keys defined in other packages.
  104. // type key int
  105. //
  106. // // userKey is the key for user.User values in Contexts. It is
  107. // // unexported; clients use user.NewContext and user.FromContext
  108. // // instead of using this key directly.
  109. // var userKey key = 0
  110. //
  111. // // NewContext returns a new Context that carries value u.
  112. // func NewContext(ctx context.Context, u *User) context.Context {
  113. // return context.WithValue(userKey, u)
  114. // }
  115. //
  116. // // FromContext returns the User value stored in ctx, if any.
  117. // func FromContext(ctx context.Context) (*User, bool) {
  118. // u, ok := ctx.Value(userKey).(*User)
  119. // return u, ok
  120. // }
  121. Value(key interface{}) interface{}
  122. }
  123. // Canceled is the error returned by Context.Err when the context is canceled.
  124. var Canceled = errors.New("context canceled")
  125. // DeadlineExceeded is the error returned by Context.Err when the context's
  126. // deadline passes.
  127. var DeadlineExceeded = errors.New("context deadline exceeded")
  128. // A ctx is a Context that automatically propagates cancellation signals to
  129. // other ctxs (those created using this ctx as their parent). A ctx also
  130. // manages its own deadline timer.
  131. type ctx struct {
  132. parent Context // set by newCtx
  133. done chan struct{} // closed by the first cancel call. nil if uncancelable.
  134. key interface{} // set by WithValue
  135. val interface{} // set by WithValue
  136. deadline time.Time // set by WithDeadline
  137. deadlineSet bool // set by WithDeadline
  138. // parent.mu ACQUIRED_BEFORE mu: mu must not be held when acquiring parent.mu.
  139. mu sync.RWMutex
  140. children map[*ctx]bool // set to nil by the first cancel call
  141. err error // set to non-nil by the first cancel call
  142. timer *time.Timer // set by WithDeadline, read by cancel
  143. }
  144. func (c *ctx) Deadline() (deadline time.Time, ok bool) {
  145. return c.deadline, c.deadlineSet
  146. }
  147. func (c *ctx) Done() <-chan struct{} {
  148. return c.done // may be nil
  149. }
  150. func (c *ctx) Err() error {
  151. c.mu.RLock() // c.err is under mu
  152. defer c.mu.RUnlock()
  153. return c.err
  154. }
  155. func (c *ctx) Value(key interface{}) interface{} {
  156. if c.key == key {
  157. return c.val
  158. }
  159. if c.parent != nil {
  160. return c.parent.Value(key)
  161. }
  162. return nil
  163. }
  164. // The background context for this process.
  165. var background = newCtx(nil, neverCanceled)
  166. // Background returns an ambient background context, which is never nil. This
  167. // context represents the intrinsic state of the application at startup time,
  168. // independent of any incoming request state.
  169. //
  170. // The Background context is typically only used by the main function and tests.
  171. func Background() Context {
  172. return background
  173. }
  174. // TODO returns an ambient background context, which is never nil. Code should
  175. // use context.TODO when it's unclear which Context to use or it's is not yet
  176. // available (because the surrounding function has not yet been extended to
  177. // accept a Context parameter). TODO is recognized by static analysis tools
  178. // that determine whether Contexts are propagated correctly in a program.
  179. func TODO() Context {
  180. return Background()
  181. }
  182. // A CancelFunc tells an operation to abandon its work.
  183. // A CancelFunc does not wait for the work to stop.
  184. // After the first, subsequent calls to a CancelFunc do nothing.
  185. type CancelFunc func()
  186. // WithCancel returns a copy of parent with a new Done channel. The returned
  187. // context's Done channel is closed when the returned cancel function is called
  188. // or when the parent context's Done channel is closed, whichever happens first.
  189. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  190. return withCancel(parent)
  191. }
  192. func withCancel(parent Context) (*ctx, CancelFunc) {
  193. c := newCtx(parent, maybeCanceled)
  194. return c, func() { c.cancel(true, Canceled) }
  195. }
  196. // WithDeadline returns a copy of the parent context with the deadline adjusted
  197. // to be no later than d. If the parent's deadline is already earlier than d,
  198. // WithDeadline(parent, d) is semantically equivalent to parent. The returned
  199. // context's Done channel is closed when the deadline expires, when the returned
  200. // cancel function is called, or when the parent context's Done channel is
  201. // closed, whichever happens first.
  202. //
  203. // Cancelling this context releases resources associated with the deadline
  204. // timer, so code should call cancel as soon as the operations running in this
  205. // Context complete.
  206. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
  207. c, cancel := withCancel(parent)
  208. if cur, ok := c.Deadline(); ok && cur.Before(deadline) {
  209. // The current deadline is already sooner than the new one.
  210. return c, cancel
  211. }
  212. c.deadline, c.deadlineSet = deadline, true
  213. d := deadline.Sub(time.Now())
  214. if d <= 0 {
  215. // TODO(sameer): pass removeFromParent=true here?
  216. c.cancel(false, DeadlineExceeded) // deadline has already passed
  217. return c, cancel
  218. }
  219. c.mu.Lock()
  220. defer c.mu.Unlock()
  221. c.timer = time.AfterFunc(d, func() {
  222. // TODO(sameer): pass removeFromParent=true here?
  223. c.cancel(false, DeadlineExceeded)
  224. })
  225. return c, cancel
  226. }
  227. // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  228. //
  229. // Cancelling this context releases resources associated with the deadline
  230. // timer, so code should call cancel as soon as the operations running in this
  231. // Context complete:
  232. //
  233. // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  234. // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  235. // defer cancel() // releases resources if slowOperation completes before timeout elapses
  236. // return slowOperation(ctx)
  237. // }
  238. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  239. return WithDeadline(parent, time.Now().Add(timeout))
  240. }
  241. // WithValue returns a copy of parent in which the value associated with key is
  242. // val.
  243. //
  244. // Use context Values only for request-scoped data that transits processes and
  245. // APIs, not for passing optional parameters to functions.
  246. func WithValue(parent Context, key interface{}, val interface{}) Context {
  247. c := newCtx(parent, neverCanceled)
  248. c.key, c.val = key, val
  249. return c
  250. }
  251. const maybeCanceled = true
  252. const neverCanceled = false
  253. func newCtx(parent Context, childMayCancel bool) *ctx {
  254. c := &ctx{parent: parent}
  255. parentMayCancel := parent != nil && parent.Done() != nil
  256. if childMayCancel || parentMayCancel {
  257. c.done = make(chan struct{})
  258. }
  259. if parent != nil {
  260. c.deadline, c.deadlineSet = parent.Deadline()
  261. }
  262. if parentMayCancel {
  263. if p, ok := parent.(*ctx); ok {
  264. // Arrange for the new ctx to be canceled when the parent is.
  265. p.mu.Lock()
  266. if p.err != nil {
  267. // parent has already been canceled
  268. c.cancel(false, p.err)
  269. } else {
  270. if p.children == nil {
  271. p.children = make(map[*ctx]bool)
  272. }
  273. p.children[c] = true
  274. }
  275. p.mu.Unlock()
  276. } else {
  277. // Cancel the new ctx when context.Done is closed.
  278. go func() {
  279. select {
  280. case <-parent.Done():
  281. c.cancel(false, parent.Err())
  282. case <-c.done:
  283. }
  284. }()
  285. }
  286. }
  287. return c
  288. }
  289. // cancel closes c.done, cancels each of this ctx's children, and, if
  290. // removeFromParent is true, removes this ctx from its parent's children.
  291. // cancel stops c.timer, if it is running.
  292. func (c *ctx) cancel(removeFromParent bool, err error) {
  293. if err == nil {
  294. panic("context: internal error: missing cancel error")
  295. }
  296. c.mu.Lock()
  297. if c.done == nil {
  298. panic("context: internal error: missing done channel")
  299. }
  300. if c.err != nil {
  301. c.mu.Unlock()
  302. return // already canceled
  303. }
  304. if c.timer != nil {
  305. c.timer.Stop()
  306. c.timer = nil
  307. }
  308. close(c.done)
  309. c.err = err
  310. for child := range c.children {
  311. // NOTE: acquiring the child's lock while holding parent's lock.
  312. child.cancel(false, err)
  313. }
  314. c.children = nil
  315. c.mu.Unlock()
  316. if p, ok := c.parent.(*ctx); ok && p != nil && removeFromParent {
  317. p.mu.Lock()
  318. if p.children != nil {
  319. delete(p.children, c)
  320. }
  321. p.mu.Unlock()
  322. }
  323. }