context.go 14 KB

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