context.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 // import "golang.org/x/net/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's 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. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  190. c := newCancelCtx(parent)
  191. propagateCancel(parent, &c)
  192. return &c, func() { c.cancel(true, Canceled) }
  193. }
  194. // newCancelCtx returns an initialized cancelCtx.
  195. func newCancelCtx(parent Context) cancelCtx {
  196. return cancelCtx{
  197. Context: parent,
  198. done: make(chan struct{}),
  199. }
  200. }
  201. // propagateCancel arranges for child to be canceled when parent is.
  202. func propagateCancel(parent Context, child canceler) {
  203. if parent.Done() == nil {
  204. return // parent is never canceled
  205. }
  206. if p, ok := parentCancelCtx(parent); ok {
  207. p.mu.Lock()
  208. if p.err != nil {
  209. // parent has already been canceled
  210. child.cancel(false, p.err)
  211. } else {
  212. if p.children == nil {
  213. p.children = make(map[canceler]bool)
  214. }
  215. p.children[child] = true
  216. }
  217. p.mu.Unlock()
  218. } else {
  219. go func() {
  220. select {
  221. case <-parent.Done():
  222. child.cancel(false, parent.Err())
  223. case <-child.Done():
  224. }
  225. }()
  226. }
  227. }
  228. // parentCancelCtx follows a chain of parent references until it finds a
  229. // *cancelCtx. This function understands how each of the concrete types in this
  230. // package represents its parent.
  231. func parentCancelCtx(parent Context) (*cancelCtx, bool) {
  232. for {
  233. switch c := parent.(type) {
  234. case *cancelCtx:
  235. return c, true
  236. case *timerCtx:
  237. return &c.cancelCtx, true
  238. case *valueCtx:
  239. parent = c.Context
  240. default:
  241. return nil, false
  242. }
  243. }
  244. }
  245. // removeChild removes a context from its parent.
  246. func removeChild(parent Context, child canceler) {
  247. p, ok := parentCancelCtx(parent)
  248. if !ok {
  249. return
  250. }
  251. p.mu.Lock()
  252. if p.children != nil {
  253. delete(p.children, child)
  254. }
  255. p.mu.Unlock()
  256. }
  257. // A canceler is a context type that can be canceled directly. The
  258. // implementations are *cancelCtx and *timerCtx.
  259. type canceler interface {
  260. cancel(removeFromParent bool, err error)
  261. Done() <-chan struct{}
  262. }
  263. // A cancelCtx can be canceled. When canceled, it also cancels any children
  264. // that implement canceler.
  265. type cancelCtx struct {
  266. Context
  267. done chan struct{} // closed by the first cancel call.
  268. mu sync.Mutex
  269. children map[canceler]bool // set to nil by the first cancel call
  270. err error // set to non-nil by the first cancel call
  271. }
  272. func (c *cancelCtx) Done() <-chan struct{} {
  273. return c.done
  274. }
  275. func (c *cancelCtx) Err() error {
  276. c.mu.Lock()
  277. defer c.mu.Unlock()
  278. return c.err
  279. }
  280. func (c *cancelCtx) String() string {
  281. return fmt.Sprintf("%v.WithCancel", c.Context)
  282. }
  283. // cancel closes c.done, cancels each of c's children, and, if
  284. // removeFromParent is true, removes c from its parent's children.
  285. func (c *cancelCtx) cancel(removeFromParent bool, err error) {
  286. if err == nil {
  287. panic("context: internal error: missing cancel error")
  288. }
  289. c.mu.Lock()
  290. if c.err != nil {
  291. c.mu.Unlock()
  292. return // already canceled
  293. }
  294. c.err = err
  295. close(c.done)
  296. for child := range c.children {
  297. // NOTE: acquiring the child's lock while holding parent's lock.
  298. child.cancel(false, err)
  299. }
  300. c.children = nil
  301. c.mu.Unlock()
  302. if removeFromParent {
  303. removeChild(c.Context, c)
  304. }
  305. }
  306. // WithDeadline returns a copy of the parent context with the deadline adjusted
  307. // to be no later than d. If the parent's deadline is already earlier than d,
  308. // WithDeadline(parent, d) is semantically equivalent to parent. The returned
  309. // context's Done channel is closed when the deadline expires, when the returned
  310. // cancel function is called, or when the parent context's Done channel is
  311. // closed, whichever happens first.
  312. //
  313. // Canceling this context releases resources associated with the deadline
  314. // timer, so code should call cancel as soon as the operations running in this
  315. // Context complete.
  316. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
  317. if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
  318. // The current deadline is already sooner than the new one.
  319. return WithCancel(parent)
  320. }
  321. c := &timerCtx{
  322. cancelCtx: newCancelCtx(parent),
  323. deadline: deadline,
  324. }
  325. propagateCancel(parent, c)
  326. d := deadline.Sub(time.Now())
  327. if d <= 0 {
  328. c.cancel(true, DeadlineExceeded) // deadline has already passed
  329. return c, func() { c.cancel(true, Canceled) }
  330. }
  331. c.mu.Lock()
  332. defer c.mu.Unlock()
  333. if c.err == nil {
  334. c.timer = time.AfterFunc(d, func() {
  335. c.cancel(true, DeadlineExceeded)
  336. })
  337. }
  338. return c, func() { c.cancel(true, Canceled) }
  339. }
  340. // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
  341. // implement Done and Err. It implements cancel by stopping its timer then
  342. // delegating to cancelCtx.cancel.
  343. type timerCtx struct {
  344. cancelCtx
  345. timer *time.Timer // Under cancelCtx.mu.
  346. deadline time.Time
  347. }
  348. func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
  349. return c.deadline, true
  350. }
  351. func (c *timerCtx) String() string {
  352. return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now()))
  353. }
  354. func (c *timerCtx) cancel(removeFromParent bool, err error) {
  355. c.cancelCtx.cancel(false, err)
  356. if removeFromParent {
  357. // Remove this timerCtx from its parent cancelCtx's children.
  358. removeChild(c.cancelCtx.Context, c)
  359. }
  360. c.mu.Lock()
  361. if c.timer != nil {
  362. c.timer.Stop()
  363. c.timer = nil
  364. }
  365. c.mu.Unlock()
  366. }
  367. // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  368. //
  369. // Canceling this context releases resources associated with the deadline
  370. // timer, so code should call cancel as soon as the operations running in this
  371. // Context complete:
  372. //
  373. // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  374. // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  375. // defer cancel() // releases resources if slowOperation completes before timeout elapses
  376. // return slowOperation(ctx)
  377. // }
  378. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  379. return WithDeadline(parent, time.Now().Add(timeout))
  380. }
  381. // WithValue returns a copy of parent in which the value associated with key is
  382. // val.
  383. //
  384. // Use context Values only for request-scoped data that transits processes and
  385. // APIs, not for passing optional parameters to functions.
  386. func WithValue(parent Context, key interface{}, val interface{}) Context {
  387. return &valueCtx{parent, key, val}
  388. }
  389. // A valueCtx carries a key-value pair. It implements Value for that key and
  390. // delegates all other calls to the embedded Context.
  391. type valueCtx struct {
  392. Context
  393. key, val interface{}
  394. }
  395. func (c *valueCtx) String() string {
  396. return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val)
  397. }
  398. func (c *valueCtx) Value(key interface{}) interface{} {
  399. if c.key == key {
  400. return c.val
  401. }
  402. return c.Context.Value(key)
  403. }