context.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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,
  5. // cancelation signals, and other request-scoped values across API boundaries
  6. // and between processes.
  7. //
  8. // Incoming requests to a server should create a Context, and outgoing calls to
  9. // servers should accept a Context. The chain of function calls between must
  10. // propagate the Context, optionally replacing it with a modified copy created
  11. // using 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. //
  34. // See http://blog.golang.org/context for example code for a server that uses
  35. // Contexts.
  36. package context
  37. import (
  38. "errors"
  39. "fmt"
  40. "sync"
  41. "time"
  42. )
  43. // A Context carries a deadline, a cancelation signal, and other values across
  44. // API boundaries.
  45. //
  46. // Context's methods may be called by multiple goroutines simultaneously.
  47. type Context interface {
  48. // Deadline returns the time when work done on behalf of this context
  49. // should be canceled. Deadline returns ok==false when no deadline is
  50. // set. Successive calls to Deadline return the same results.
  51. Deadline() (deadline time.Time, ok bool)
  52. // Done returns a channel that's closed when work done on behalf of this
  53. // context should be canceled. Done may return nil if this context can
  54. // never be canceled. Successive calls to Done return the same value.
  55. //
  56. // WithCancel arranges for Done to be closed when cancel is called;
  57. // WithDeadline arranges for Done to be closed when the deadline
  58. // expires; WithTimeout arranges for Done to be closed when the timeout
  59. // elapses.
  60. //
  61. // Done is provided for use in select statements:
  62. //
  63. // // DoSomething calls DoSomethingSlow and returns as soon as
  64. // // it returns or ctx.Done is closed.
  65. // func DoSomething(ctx context.Context) (Result, error) {
  66. // c := make(chan Result, 1)
  67. // go func() { c <- DoSomethingSlow(ctx) }()
  68. // select {
  69. // case res := <-c:
  70. // return res, nil
  71. // case <-ctx.Done():
  72. // return nil, ctx.Err()
  73. // }
  74. // }
  75. //
  76. // See http://blog.golang.org/pipelines for more examples of how to use
  77. // a Done channel for cancelation.
  78. Done() <-chan struct{}
  79. // Err returns a non-nil error value after Done is closed. Err returns
  80. // Canceled if the context was canceled or DeadlineExceeded if the
  81. // context's deadline passed. No other values for Err are defined.
  82. // After Done is closed, successive calls to Err return the same value.
  83. Err() error
  84. // Value returns the value associated with this context for key, or nil
  85. // if no value is associated with key. Successive calls to Value with
  86. // the same key returns the same result.
  87. //
  88. // Use context values only for request-scoped data that transits
  89. // processes and API boundaries, not for passing optional parameters to
  90. // functions.
  91. //
  92. // A key identifies a specific value in a Context. Functions that wish
  93. // to store values in Context typically allocate a key in a global
  94. // variable then use that key as the argument to context.WithValue and
  95. // Context.Value. A key can be any type that supports equality;
  96. // packages should define keys as an unexported type to avoid
  97. // collisions.
  98. //
  99. // Packages that define a Context key should provide type-safe accessors
  100. // for the values stores using that key:
  101. //
  102. // // Package user defines a User type that's stored in Contexts.
  103. // package user
  104. //
  105. // import "code.google.com/p/go.net/context"
  106. //
  107. // // User is the type of value stored in the Contexts.
  108. // type User struct {...}
  109. //
  110. // // key is an unexported type for keys defined in this package.
  111. // // This prevents collisions with keys defined in other packages.
  112. // type key int
  113. //
  114. // // userKey is the key for user.User values in Contexts. It is
  115. // // unexported; clients use user.NewContext and user.FromContext
  116. // // instead of using this key directly.
  117. // var userKey key = 0
  118. //
  119. // // NewContext returns a new Context that carries value u.
  120. // func NewContext(ctx context.Context, u *User) context.Context {
  121. // return context.WithValue(userKey, u)
  122. // }
  123. //
  124. // // FromContext returns the User value stored in ctx, if any.
  125. // func FromContext(ctx context.Context) (*User, bool) {
  126. // u, ok := ctx.Value(userKey).(*User)
  127. // return u, ok
  128. // }
  129. Value(key interface{}) interface{}
  130. }
  131. // Canceled is the error returned by Context.Err when the context is canceled.
  132. var Canceled = errors.New("context canceled")
  133. // DeadlineExceeded is the error returned by Context.Err when the context's
  134. // deadline passes.
  135. var DeadlineExceeded = errors.New("context deadline exceeded")
  136. // An emptyCtx is never canceled, has no values, and has no deadline.
  137. type emptyCtx int
  138. func (emptyCtx) Deadline() (deadline time.Time, ok bool) {
  139. return
  140. }
  141. func (emptyCtx) Done() <-chan struct{} {
  142. return nil
  143. }
  144. func (emptyCtx) Err() error {
  145. return nil
  146. }
  147. func (emptyCtx) Value(key interface{}) interface{} {
  148. return nil
  149. }
  150. func (n emptyCtx) String() string {
  151. switch n {
  152. case background:
  153. return "context.Background"
  154. case todo:
  155. return "context.TODO"
  156. }
  157. return "unknown empty Context"
  158. }
  159. const (
  160. background emptyCtx = 1
  161. todo emptyCtx = 2
  162. )
  163. // Background returns a non-nil, empty Context. It is never canceled, has no
  164. // values, and has no deadline. It is typically used by the main function,
  165. // initialization, and tests, and as the top-level Context for incoming
  166. // requests.
  167. func Background() Context {
  168. return background
  169. }
  170. // TODO returns a non-nil, empty Context. Code should use context.TODO when
  171. // it's unclear which Context to use or it's is not yet available (because the
  172. // surrounding function has not yet been extended to accept a Context
  173. // parameter). TODO is recognized by static analysis tools that determine
  174. // whether Contexts are propagated correctly in a program.
  175. func TODO() Context {
  176. return todo
  177. }
  178. // A CancelFunc tells an operation to abandon its work.
  179. // A CancelFunc does not wait for the work to stop.
  180. // After the first call, subsequent calls to a CancelFunc do nothing.
  181. type CancelFunc func()
  182. // WithCancel returns a copy of parent with a new Done channel. The returned
  183. // context's Done channel is closed when the returned cancel function is called
  184. // or when the parent context's Done channel is closed, whichever happens first.
  185. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  186. c := newCancelCtx(parent)
  187. propagateCancel(parent, &c)
  188. return &c, func() { c.cancel(true, Canceled) }
  189. }
  190. // newCancelCtx returns an initialized cancelCtx.
  191. func newCancelCtx(parent Context) cancelCtx {
  192. return cancelCtx{
  193. Context: parent,
  194. done: make(chan struct{}),
  195. }
  196. }
  197. // propagateCancel arranges for child to be canceled when parent is.
  198. func propagateCancel(parent Context, child canceler) {
  199. if parent.Done() == nil {
  200. return // parent is never canceled
  201. }
  202. if p, ok := parentCancelCtx(parent); ok {
  203. p.mu.Lock()
  204. if p.err != nil {
  205. // parent has already been canceled
  206. child.cancel(false, p.err)
  207. } else {
  208. if p.children == nil {
  209. p.children = make(map[canceler]bool)
  210. }
  211. p.children[child] = true
  212. }
  213. p.mu.Unlock()
  214. } else {
  215. go func() {
  216. select {
  217. case <-parent.Done():
  218. child.cancel(false, parent.Err())
  219. case <-child.Done():
  220. }
  221. }()
  222. }
  223. }
  224. // parentCancelCtx follows a chain of parent references until it finds a
  225. // *cancelCtx. This function understands how each of the concrete types in this
  226. // package represents its parent.
  227. func parentCancelCtx(parent Context) (*cancelCtx, bool) {
  228. for {
  229. switch c := parent.(type) {
  230. case *cancelCtx:
  231. return c, true
  232. case *timerCtx:
  233. return &c.cancelCtx, true
  234. case *valueCtx:
  235. parent = c.Context
  236. default:
  237. return nil, false
  238. }
  239. }
  240. }
  241. // A canceler is a context type that can be canceled directly. The
  242. // implementations are *cancelCtx and *timerCtx.
  243. type canceler interface {
  244. cancel(removeFromParent bool, err error)
  245. Done() <-chan struct{}
  246. }
  247. // A cancelCtx can be canceled. When canceled, it also cancels any children
  248. // that implement canceler.
  249. type cancelCtx struct {
  250. Context
  251. done chan struct{} // closed by the first cancel call.
  252. mu sync.Mutex
  253. children map[canceler]bool // set to nil by the first cancel call
  254. err error // set to non-nil by the first cancel call
  255. }
  256. func (c *cancelCtx) Done() <-chan struct{} {
  257. return c.done
  258. }
  259. func (c *cancelCtx) Err() error {
  260. c.mu.Lock()
  261. defer c.mu.Unlock()
  262. return c.err
  263. }
  264. func (c *cancelCtx) String() string {
  265. return fmt.Sprintf("%v.WithCancel", c.Context)
  266. }
  267. // cancel closes c.done, cancels each of c's children, and, if
  268. // removeFromParent is true, removes c from its parent's children.
  269. func (c *cancelCtx) cancel(removeFromParent bool, err error) {
  270. if err == nil {
  271. panic("context: internal error: missing cancel error")
  272. }
  273. c.mu.Lock()
  274. if c.err != nil {
  275. c.mu.Unlock()
  276. return // already canceled
  277. }
  278. c.err = err
  279. close(c.done)
  280. for child := range c.children {
  281. // NOTE: acquiring the child's lock while holding parent's lock.
  282. child.cancel(false, err)
  283. }
  284. c.children = nil
  285. c.mu.Unlock()
  286. if removeFromParent {
  287. if p, ok := parentCancelCtx(c.Context); ok {
  288. p.mu.Lock()
  289. if p.children != nil {
  290. delete(p.children, c)
  291. }
  292. p.mu.Unlock()
  293. }
  294. }
  295. }
  296. // WithDeadline returns a copy of the parent context with the deadline adjusted
  297. // to be no later than d. If the parent's deadline is already earlier than d,
  298. // WithDeadline(parent, d) is semantically equivalent to parent. The returned
  299. // context's Done channel is closed when the deadline expires, when the returned
  300. // cancel function is called, or when the parent context's Done channel is
  301. // closed, whichever happens first.
  302. //
  303. // Canceling this context releases resources associated with the deadline
  304. // timer, so code should call cancel as soon as the operations running in this
  305. // Context complete.
  306. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
  307. if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
  308. // The current deadline is already sooner than the new one.
  309. return WithCancel(parent)
  310. }
  311. c := &timerCtx{
  312. cancelCtx: newCancelCtx(parent),
  313. deadline: deadline,
  314. }
  315. propagateCancel(parent, c)
  316. d := deadline.Sub(time.Now())
  317. if d <= 0 {
  318. c.cancel(true, DeadlineExceeded) // deadline has already passed
  319. return c, func() { c.cancel(true, Canceled) }
  320. }
  321. c.mu.Lock()
  322. defer c.mu.Unlock()
  323. if c.err == nil {
  324. c.timer = time.AfterFunc(d, func() {
  325. c.cancel(true, DeadlineExceeded)
  326. })
  327. }
  328. return c, func() { c.cancel(true, Canceled) }
  329. }
  330. // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
  331. // implement Done and Err. It implements cancel by stopping its timer then
  332. // delegating to cancelCtx.cancel.
  333. type timerCtx struct {
  334. cancelCtx
  335. timer *time.Timer // Under cancelCtx.mu.
  336. deadline time.Time
  337. }
  338. func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
  339. return c.deadline, true
  340. }
  341. func (c *timerCtx) String() string {
  342. return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now()))
  343. }
  344. func (c *timerCtx) cancel(removeFromParent bool, err error) {
  345. c.cancelCtx.cancel(removeFromParent, err)
  346. c.mu.Lock()
  347. if c.timer != nil {
  348. c.timer.Stop()
  349. c.timer = nil
  350. }
  351. c.mu.Unlock()
  352. }
  353. // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  354. //
  355. // Canceling this context releases resources associated with the deadline
  356. // timer, so code should call cancel as soon as the operations running in this
  357. // Context complete:
  358. //
  359. // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  360. // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  361. // defer cancel() // releases resources if slowOperation completes before timeout elapses
  362. // return slowOperation(ctx)
  363. // }
  364. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  365. return WithDeadline(parent, time.Now().Add(timeout))
  366. }
  367. // WithValue returns a copy of parent in which the value associated with key is
  368. // val.
  369. //
  370. // Use context Values only for request-scoped data that transits processes and
  371. // APIs, not for passing optional parameters to functions.
  372. func WithValue(parent Context, key interface{}, val interface{}) Context {
  373. return &valueCtx{parent, key, val}
  374. }
  375. // A valueCtx carries a key-value pair. It implements Value for that key and
  376. // delegates all other calls to the embedded Context.
  377. type valueCtx struct {
  378. Context
  379. key, val interface{}
  380. }
  381. func (c *valueCtx) String() string {
  382. return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val)
  383. }
  384. func (c *valueCtx) Value(key interface{}) interface{} {
  385. if c.key == key {
  386. return c.val
  387. }
  388. return c.Context.Value(key)
  389. }