context.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. // // 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 "golang.org/x/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(ctx, 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. It is not
  137. // struct{}, since vars of this type must have distinct addresses.
  138. type emptyCtx int
  139. func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
  140. return
  141. }
  142. func (*emptyCtx) Done() <-chan struct{} {
  143. return nil
  144. }
  145. func (*emptyCtx) Err() error {
  146. return nil
  147. }
  148. func (*emptyCtx) Value(key interface{}) interface{} {
  149. return nil
  150. }
  151. func (e *emptyCtx) String() string {
  152. switch e {
  153. case background:
  154. return "context.Background"
  155. case todo:
  156. return "context.TODO"
  157. }
  158. return "unknown empty Context"
  159. }
  160. var (
  161. background = new(emptyCtx)
  162. todo = new(emptyCtx)
  163. )
  164. // Background returns a non-nil, empty Context. It is never canceled, has no
  165. // values, and has no deadline. It is typically used by the main function,
  166. // initialization, and tests, and as the top-level Context for incoming
  167. // requests.
  168. func Background() Context {
  169. return background
  170. }
  171. // TODO returns a non-nil, empty Context. Code should use context.TODO when
  172. // it's unclear which Context to use or it's is not yet available (because the
  173. // surrounding function has not yet been extended to accept a Context
  174. // parameter). TODO is recognized by static analysis tools that determine
  175. // whether Contexts are propagated correctly in a program.
  176. func TODO() Context {
  177. return todo
  178. }
  179. // A CancelFunc tells an operation to abandon its work.
  180. // A CancelFunc does not wait for the work to stop.
  181. // After the first call, subsequent calls to a CancelFunc do nothing.
  182. type CancelFunc func()
  183. // WithCancel returns a copy of parent with a new Done channel. The returned
  184. // context's Done channel is closed when the returned cancel function is called
  185. // or when the parent context's Done channel is closed, whichever happens first.
  186. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  187. c := newCancelCtx(parent)
  188. propagateCancel(parent, &c)
  189. return &c, func() { c.cancel(true, Canceled) }
  190. }
  191. // newCancelCtx returns an initialized cancelCtx.
  192. func newCancelCtx(parent Context) cancelCtx {
  193. return cancelCtx{
  194. Context: parent,
  195. done: make(chan struct{}),
  196. }
  197. }
  198. // propagateCancel arranges for child to be canceled when parent is.
  199. func propagateCancel(parent Context, child canceler) {
  200. if parent.Done() == nil {
  201. return // parent is never canceled
  202. }
  203. if p, ok := parentCancelCtx(parent); ok {
  204. p.mu.Lock()
  205. if p.err != nil {
  206. // parent has already been canceled
  207. child.cancel(false, p.err)
  208. } else {
  209. if p.children == nil {
  210. p.children = make(map[canceler]bool)
  211. }
  212. p.children[child] = true
  213. }
  214. p.mu.Unlock()
  215. } else {
  216. go func() {
  217. select {
  218. case <-parent.Done():
  219. child.cancel(false, parent.Err())
  220. case <-child.Done():
  221. }
  222. }()
  223. }
  224. }
  225. // parentCancelCtx follows a chain of parent references until it finds a
  226. // *cancelCtx. This function understands how each of the concrete types in this
  227. // package represents its parent.
  228. func parentCancelCtx(parent Context) (*cancelCtx, bool) {
  229. for {
  230. switch c := parent.(type) {
  231. case *cancelCtx:
  232. return c, true
  233. case *timerCtx:
  234. return &c.cancelCtx, true
  235. case *valueCtx:
  236. parent = c.Context
  237. default:
  238. return nil, false
  239. }
  240. }
  241. }
  242. // A canceler is a context type that can be canceled directly. The
  243. // implementations are *cancelCtx and *timerCtx.
  244. type canceler interface {
  245. cancel(removeFromParent bool, err error)
  246. Done() <-chan struct{}
  247. }
  248. // A cancelCtx can be canceled. When canceled, it also cancels any children
  249. // that implement canceler.
  250. type cancelCtx struct {
  251. Context
  252. done chan struct{} // closed by the first cancel call.
  253. mu sync.Mutex
  254. children map[canceler]bool // set to nil by the first cancel call
  255. err error // set to non-nil by the first cancel call
  256. }
  257. func (c *cancelCtx) Done() <-chan struct{} {
  258. return c.done
  259. }
  260. func (c *cancelCtx) Err() error {
  261. c.mu.Lock()
  262. defer c.mu.Unlock()
  263. return c.err
  264. }
  265. func (c *cancelCtx) String() string {
  266. return fmt.Sprintf("%v.WithCancel", c.Context)
  267. }
  268. // cancel closes c.done, cancels each of c's children, and, if
  269. // removeFromParent is true, removes c from its parent's children.
  270. func (c *cancelCtx) cancel(removeFromParent bool, err error) {
  271. if err == nil {
  272. panic("context: internal error: missing cancel error")
  273. }
  274. c.mu.Lock()
  275. if c.err != nil {
  276. c.mu.Unlock()
  277. return // already canceled
  278. }
  279. c.err = err
  280. close(c.done)
  281. for child := range c.children {
  282. // NOTE: acquiring the child's lock while holding parent's lock.
  283. child.cancel(false, err)
  284. }
  285. c.children = nil
  286. c.mu.Unlock()
  287. if removeFromParent {
  288. if p, ok := parentCancelCtx(c.Context); ok {
  289. p.mu.Lock()
  290. if p.children != nil {
  291. delete(p.children, c)
  292. }
  293. p.mu.Unlock()
  294. }
  295. }
  296. }
  297. // WithDeadline returns a copy of the parent context with the deadline adjusted
  298. // to be no later than d. If the parent's deadline is already earlier than d,
  299. // WithDeadline(parent, d) is semantically equivalent to parent. The returned
  300. // context's Done channel is closed when the deadline expires, when the returned
  301. // cancel function is called, or when the parent context's Done channel is
  302. // closed, whichever happens first.
  303. //
  304. // Canceling this context releases resources associated with the deadline
  305. // timer, so code should call cancel as soon as the operations running in this
  306. // Context complete.
  307. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
  308. if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
  309. // The current deadline is already sooner than the new one.
  310. return WithCancel(parent)
  311. }
  312. c := &timerCtx{
  313. cancelCtx: newCancelCtx(parent),
  314. deadline: deadline,
  315. }
  316. propagateCancel(parent, c)
  317. d := deadline.Sub(time.Now())
  318. if d <= 0 {
  319. c.cancel(true, DeadlineExceeded) // deadline has already passed
  320. return c, func() { c.cancel(true, Canceled) }
  321. }
  322. c.mu.Lock()
  323. defer c.mu.Unlock()
  324. if c.err == nil {
  325. c.timer = time.AfterFunc(d, func() {
  326. c.cancel(true, DeadlineExceeded)
  327. })
  328. }
  329. return c, func() { c.cancel(true, Canceled) }
  330. }
  331. // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
  332. // implement Done and Err. It implements cancel by stopping its timer then
  333. // delegating to cancelCtx.cancel.
  334. type timerCtx struct {
  335. cancelCtx
  336. timer *time.Timer // Under cancelCtx.mu.
  337. deadline time.Time
  338. }
  339. func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
  340. return c.deadline, true
  341. }
  342. func (c *timerCtx) String() string {
  343. return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now()))
  344. }
  345. func (c *timerCtx) cancel(removeFromParent bool, err error) {
  346. c.cancelCtx.cancel(removeFromParent, err)
  347. c.mu.Lock()
  348. if c.timer != nil {
  349. c.timer.Stop()
  350. c.timer = nil
  351. }
  352. c.mu.Unlock()
  353. }
  354. // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  355. //
  356. // Canceling this context releases resources associated with the deadline
  357. // timer, so code should call cancel as soon as the operations running in this
  358. // Context complete:
  359. //
  360. // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  361. // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  362. // defer cancel() // releases resources if slowOperation completes before timeout elapses
  363. // return slowOperation(ctx)
  364. // }
  365. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  366. return WithDeadline(parent, time.Now().Add(timeout))
  367. }
  368. // WithValue returns a copy of parent in which the value associated with key is
  369. // val.
  370. //
  371. // Use context Values only for request-scoped data that transits processes and
  372. // APIs, not for passing optional parameters to functions.
  373. func WithValue(parent Context, key interface{}, val interface{}) Context {
  374. return &valueCtx{parent, key, val}
  375. }
  376. // A valueCtx carries a key-value pair. It implements Value for that key and
  377. // delegates all other calls to the embedded Context.
  378. type valueCtx struct {
  379. Context
  380. key, val interface{}
  381. }
  382. func (c *valueCtx) String() string {
  383. return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val)
  384. }
  385. func (c *valueCtx) Value(key interface{}) interface{} {
  386. if c.key == key {
  387. return c.val
  388. }
  389. return c.Context.Value(key)
  390. }