context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. //
  132. // TODO(sameer): split this into separate concrete types for WithValue,
  133. // WithCancel, and WithTimeout/Deadline. This reduces the size of the structs;
  134. // for example, we don't need a timer field when creating a Context using
  135. // WithValue.
  136. type ctx struct {
  137. parent Context // set by newCtx
  138. done chan struct{} // closed by the first cancel call. nil if uncancelable.
  139. key interface{} // set by WithValue
  140. val interface{} // set by WithValue
  141. deadline time.Time // set by WithDeadline
  142. deadlineSet bool // set by WithDeadline
  143. // parent.mu ACQUIRED_BEFORE mu: mu must not be held when acquiring parent.mu.
  144. mu sync.RWMutex
  145. children map[*ctx]bool // set to nil by the first cancel call
  146. err error // set to non-nil by the first cancel call
  147. timer *time.Timer // set by WithDeadline, read by cancel
  148. }
  149. func (c *ctx) Deadline() (deadline time.Time, ok bool) {
  150. return c.deadline, c.deadlineSet
  151. }
  152. func (c *ctx) Done() <-chan struct{} {
  153. return c.done // may be nil
  154. }
  155. func (c *ctx) Err() error {
  156. c.mu.RLock() // c.err is under mu
  157. defer c.mu.RUnlock()
  158. return c.err
  159. }
  160. func (c *ctx) Value(key interface{}) interface{} {
  161. if c.key == key {
  162. return c.val
  163. }
  164. if c.parent != nil {
  165. return c.parent.Value(key)
  166. }
  167. return nil
  168. }
  169. // The background context for this process.
  170. var background = newCtx(nil, neverCanceled)
  171. // Background returns a non-nil, empty Context. It is never canceled, has no
  172. // values, and has no deadline. It is typically used by the main function,
  173. // initialization, and tests, and as the top-level Context for incoming
  174. // requests.
  175. func Background() Context {
  176. return background
  177. }
  178. // TODO returns a non-nil, empty Context. Code should use context.TODO when
  179. // it's unclear which Context to use or it's is not yet available (because the
  180. // surrounding function has not yet been extended to accept a Context
  181. // parameter). TODO is recognized by static analysis tools that determine
  182. // whether Contexts are propagated correctly in a program.
  183. func TODO() Context {
  184. return Background()
  185. }
  186. // A CancelFunc tells an operation to abandon its work.
  187. // A CancelFunc does not wait for the work to stop.
  188. // After the first, subsequent calls to a CancelFunc do nothing.
  189. type CancelFunc func()
  190. // WithCancel returns a copy of parent with a new Done channel. The returned
  191. // context's Done channel is closed when the returned cancel function is called
  192. // or when the parent context's Done channel is closed, whichever happens first.
  193. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  194. return withCancel(parent)
  195. }
  196. func withCancel(parent Context) (*ctx, CancelFunc) {
  197. c := newCtx(parent, maybeCanceled)
  198. return c, func() { c.cancel(true, Canceled) }
  199. }
  200. // WithDeadline returns a copy of the parent context with the deadline adjusted
  201. // to be no later than d. If the parent's deadline is already earlier than d,
  202. // WithDeadline(parent, d) is semantically equivalent to parent. The returned
  203. // context's Done channel is closed when the deadline expires, when the returned
  204. // cancel function is called, or when the parent context's Done channel is
  205. // closed, whichever happens first.
  206. //
  207. // Canceling this context releases resources associated with the deadline
  208. // timer, so code should call cancel as soon as the operations running in this
  209. // Context complete.
  210. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
  211. c, cancel := withCancel(parent)
  212. if cur, ok := c.Deadline(); ok && cur.Before(deadline) {
  213. // The current deadline is already sooner than the new one.
  214. return c, cancel
  215. }
  216. c.deadline, c.deadlineSet = deadline, true
  217. d := deadline.Sub(time.Now())
  218. if d <= 0 {
  219. // TODO(sameer): pass removeFromParent=true here?
  220. c.cancel(false, DeadlineExceeded) // deadline has already passed
  221. return c, cancel
  222. }
  223. c.mu.Lock()
  224. defer c.mu.Unlock()
  225. c.timer = time.AfterFunc(d, func() {
  226. // TODO(sameer): pass removeFromParent=true here?
  227. c.cancel(false, DeadlineExceeded)
  228. })
  229. return c, cancel
  230. }
  231. // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  232. //
  233. // Canceling this context releases resources associated with the deadline
  234. // timer, so code should call cancel as soon as the operations running in this
  235. // Context complete:
  236. //
  237. // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  238. // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  239. // defer cancel() // releases resources if slowOperation completes before timeout elapses
  240. // return slowOperation(ctx)
  241. // }
  242. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  243. return WithDeadline(parent, time.Now().Add(timeout))
  244. }
  245. // WithValue returns a copy of parent in which the value associated with key is
  246. // val.
  247. //
  248. // Use context Values only for request-scoped data that transits processes and
  249. // APIs, not for passing optional parameters to functions.
  250. func WithValue(parent Context, key interface{}, val interface{}) Context {
  251. c := newCtx(parent, neverCanceled)
  252. c.key, c.val = key, val
  253. return c
  254. }
  255. const maybeCanceled = true
  256. const neverCanceled = false
  257. func newCtx(parent Context, childMayCancel bool) *ctx {
  258. c := &ctx{parent: parent}
  259. parentMayCancel := parent != nil && parent.Done() != nil
  260. if childMayCancel || parentMayCancel {
  261. c.done = make(chan struct{})
  262. }
  263. if parent != nil {
  264. c.deadline, c.deadlineSet = parent.Deadline()
  265. }
  266. if parentMayCancel {
  267. if p, ok := parent.(*ctx); ok {
  268. // Arrange for the new ctx to be canceled when the parent is.
  269. p.mu.Lock()
  270. if p.err != nil {
  271. // parent has already been canceled
  272. c.cancel(false, p.err)
  273. } else {
  274. if p.children == nil {
  275. p.children = make(map[*ctx]bool)
  276. }
  277. p.children[c] = true
  278. }
  279. p.mu.Unlock()
  280. } else {
  281. // Cancel the new ctx when context.Done is closed.
  282. go func() {
  283. select {
  284. case <-parent.Done():
  285. c.cancel(false, parent.Err())
  286. case <-c.done:
  287. }
  288. }()
  289. }
  290. }
  291. return c
  292. }
  293. // cancel closes c.done, cancels each of this ctx's children, and, if
  294. // removeFromParent is true, removes this ctx from its parent's children.
  295. // cancel stops c.timer, if it is running.
  296. func (c *ctx) cancel(removeFromParent bool, err error) {
  297. if err == nil {
  298. panic("context: internal error: missing cancel error")
  299. }
  300. c.mu.Lock()
  301. if c.done == nil {
  302. panic("context: internal error: missing done channel")
  303. }
  304. if c.err != nil {
  305. c.mu.Unlock()
  306. return // already canceled
  307. }
  308. if c.timer != nil {
  309. c.timer.Stop()
  310. c.timer = nil
  311. }
  312. close(c.done)
  313. c.err = err
  314. for child := range c.children {
  315. // NOTE: acquiring the child's lock while holding parent's lock.
  316. child.cancel(false, err)
  317. }
  318. c.children = nil
  319. c.mu.Unlock()
  320. if p, ok := c.parent.(*ctx); ok && p != nil && removeFromParent {
  321. p.mu.Lock()
  322. if p.children != nil {
  323. delete(p.children, c)
  324. }
  325. p.mu.Unlock()
  326. }
  327. }