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.
5 // Package context defines the Context type, which carries deadlines,
6 // cancellation signals, and other request-scoped values across API boundaries
7 // and between processes.
9 // Incoming requests to a server should create a Context, and outgoing
10 // calls to servers should accept a Context. The chain of function
11 // calls between them must propagate the Context, optionally replacing
12 // it with a derived Context created using WithCancel, WithDeadline,
13 // WithTimeout, or WithValue. When a Context is canceled, all
14 // Contexts derived from it are also canceled.
16 // The WithCancel, WithDeadline, and WithTimeout functions take a
17 // Context (the parent) and return a derived Context (the child) and a
18 // CancelFunc. Calling the CancelFunc cancels the child and its
19 // children, removes the parent's reference to the child, and stops
20 // any associated timers. Failing to call the CancelFunc leaks the
21 // child and its children until the parent is canceled or the timer
22 // fires. The go vet tool checks that CancelFuncs are used on all
23 // control-flow paths.
25 // The WithCancelCause function returns a CancelCauseFunc, which
26 // takes an error and records it as the cancellation cause. Calling
27 // Cause on the canceled context or any of its children retrieves
28 // the cause. If no cause is specified, Cause(ctx) returns the same
29 // value as ctx.Err().
31 // Programs that use Contexts should follow these rules to keep interfaces
32 // consistent across packages and enable static analysis tools to check context
35 // Do not store Contexts inside a struct type; instead, pass a Context
36 // explicitly to each function that needs it. The Context should be the first
37 // parameter, typically named ctx:
39 // func DoSomething(ctx context.Context, arg Arg) error {
43 // Do not pass a nil Context, even if a function permits it. Pass context.TODO
44 // if you are unsure about which Context to use.
46 // Use context Values only for request-scoped data that transits processes and
47 // APIs, not for passing optional parameters to functions.
49 // The same Context may be passed to functions running in different goroutines;
50 // Contexts are safe for simultaneous use by multiple goroutines.
52 // See https://blog.golang.org/context for example code for a server that uses
58 "internal/reflectlite"
64 // A Context carries a deadline, a cancellation signal, and other values across
67 // Context's methods may be called by multiple goroutines simultaneously.
68 type Context interface {
69 // Deadline returns the time when work done on behalf of this context
70 // should be canceled. Deadline returns ok==false when no deadline is
71 // set. Successive calls to Deadline return the same results.
72 Deadline() (deadline time.Time, ok bool)
74 // Done returns a channel that's closed when work done on behalf of this
75 // context should be canceled. Done may return nil if this context can
76 // never be canceled. Successive calls to Done return the same value.
77 // The close of the Done channel may happen asynchronously,
78 // after the cancel function returns.
80 // WithCancel arranges for Done to be closed when cancel is called;
81 // WithDeadline arranges for Done to be closed when the deadline
82 // expires; WithTimeout arranges for Done to be closed when the timeout
85 // Done is provided for use in select statements:
87 // // Stream generates values with DoSomething and sends them to out
88 // // until DoSomething returns an error or ctx.Done is closed.
89 // func Stream(ctx context.Context, out chan<- Value) error {
91 // v, err := DoSomething(ctx)
103 // See https://blog.golang.org/pipelines for more examples of how to use
104 // a Done channel for cancellation.
105 Done() <-chan struct{}
107 // If Done is not yet closed, Err returns nil.
108 // If Done is closed, Err returns a non-nil error explaining why:
109 // Canceled if the context was canceled
110 // or DeadlineExceeded if the context's deadline passed.
111 // After Err returns a non-nil error, successive calls to Err return the same error.
114 // Value returns the value associated with this context for key, or nil
115 // if no value is associated with key. Successive calls to Value with
116 // the same key returns the same result.
118 // Use context values only for request-scoped data that transits
119 // processes and API boundaries, not for passing optional parameters to
122 // A key identifies a specific value in a Context. Functions that wish
123 // to store values in Context typically allocate a key in a global
124 // variable then use that key as the argument to context.WithValue and
125 // Context.Value. A key can be any type that supports equality;
126 // packages should define keys as an unexported type to avoid
129 // Packages that define a Context key should provide type-safe accessors
130 // for the values stored using that key:
132 // // Package user defines a User type that's stored in Contexts.
137 // // User is the type of value stored in the Contexts.
138 // type User struct {...}
140 // // key is an unexported type for keys defined in this package.
141 // // This prevents collisions with keys defined in other packages.
144 // // userKey is the key for user.User values in Contexts. It is
145 // // unexported; clients use user.NewContext and user.FromContext
146 // // instead of using this key directly.
149 // // NewContext returns a new Context that carries value u.
150 // func NewContext(ctx context.Context, u *User) context.Context {
151 // return context.WithValue(ctx, userKey, u)
154 // // FromContext returns the User value stored in ctx, if any.
155 // func FromContext(ctx context.Context) (*User, bool) {
156 // u, ok := ctx.Value(userKey).(*User)
162 // Canceled is the error returned by Context.Err when the context is canceled.
163 var Canceled = errors.New("context canceled")
165 // DeadlineExceeded is the error returned by Context.Err when the context's
167 var DeadlineExceeded error = deadlineExceededError{}
169 type deadlineExceededError struct{}
171 func (deadlineExceededError) Error() string { return "context deadline exceeded" }
172 func (deadlineExceededError) Timeout() bool { return true }
173 func (deadlineExceededError) Temporary() bool { return true }
175 // An emptyCtx is never canceled, has no values, and has no deadline.
176 // It is the common base of backgroundCtx and todoCtx.
177 type emptyCtx struct{}
179 func (emptyCtx) Deadline() (deadline time.Time, ok bool) {
183 func (emptyCtx) Done() <-chan struct{} {
187 func (emptyCtx) Err() error {
191 func (emptyCtx) Value(key any) any {
195 type backgroundCtx struct{ emptyCtx }
197 func (backgroundCtx) String() string {
198 return "context.Background"
201 type todoCtx struct{ emptyCtx }
203 func (todoCtx) String() string {
204 return "context.TODO"
207 // Background returns a non-nil, empty Context. It is never canceled, has no
208 // values, and has no deadline. It is typically used by the main function,
209 // initialization, and tests, and as the top-level Context for incoming
211 func Background() Context {
212 return backgroundCtx{}
215 // TODO returns a non-nil, empty Context. Code should use context.TODO when
216 // it's unclear which Context to use or it is not yet available (because the
217 // surrounding function has not yet been extended to accept a Context
219 func TODO() Context {
223 // A CancelFunc tells an operation to abandon its work.
224 // A CancelFunc does not wait for the work to stop.
225 // A CancelFunc may be called by multiple goroutines simultaneously.
226 // After the first call, subsequent calls to a CancelFunc do nothing.
227 type CancelFunc func()
229 // WithCancel returns a copy of parent with a new Done channel. The returned
230 // context's Done channel is closed when the returned cancel function is called
231 // or when the parent context's Done channel is closed, whichever happens first.
233 // Canceling this context releases resources associated with it, so code should
234 // call cancel as soon as the operations running in this Context complete.
235 func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
236 c := withCancel(parent)
237 return c, func() { c.cancel(true, Canceled, nil) }
240 // A CancelCauseFunc behaves like a CancelFunc but additionally sets the cancellation cause.
241 // This cause can be retrieved by calling Cause on the canceled Context or on
242 // any of its derived Contexts.
244 // If the context has already been canceled, CancelCauseFunc does not set the cause.
245 // For example, if childContext is derived from parentContext:
246 // - if parentContext is canceled with cause1 before childContext is canceled with cause2,
247 // then Cause(parentContext) == Cause(childContext) == cause1
248 // - if childContext is canceled with cause2 before parentContext is canceled with cause1,
249 // then Cause(parentContext) == cause1 and Cause(childContext) == cause2
250 type CancelCauseFunc func(cause error)
252 // WithCancelCause behaves like WithCancel but returns a CancelCauseFunc instead of a CancelFunc.
253 // Calling cancel with a non-nil error (the "cause") records that error in ctx;
254 // it can then be retrieved using Cause(ctx).
255 // Calling cancel with nil sets the cause to Canceled.
259 // ctx, cancel := context.WithCancelCause(parent)
261 // ctx.Err() // returns context.Canceled
262 // context.Cause(ctx) // returns myError
263 func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc) {
264 c := withCancel(parent)
265 return c, func(cause error) { c.cancel(true, Canceled, cause) }
268 func withCancel(parent Context) *cancelCtx {
270 panic("cannot create context from nil parent")
272 c := &cancelCtx{Context: parent}
273 propagateCancel(parent, c)
277 // Cause returns a non-nil error explaining why c was canceled.
278 // The first cancellation of c or one of its parents sets the cause.
279 // If that cancellation happened via a call to CancelCauseFunc(err),
280 // then Cause returns err.
281 // Otherwise Cause(c) returns the same value as c.Err().
282 // Cause returns nil if c has not been canceled yet.
283 func Cause(c Context) error {
284 if cc, ok := c.Value(&cancelCtxKey).(*cancelCtx); ok {
292 // goroutines counts the number of goroutines ever created; for testing.
293 var goroutines atomic.Int32
295 // propagateCancel arranges for child to be canceled when parent is.
296 func propagateCancel(parent Context, child canceler) {
297 done := parent.Done()
299 return // parent is never canceled
304 // parent is already canceled
305 child.cancel(false, parent.Err(), Cause(parent))
310 if p, ok := parentCancelCtx(parent); ok {
313 // parent has already been canceled
314 child.cancel(false, p.err, p.cause)
316 if p.children == nil {
317 p.children = make(map[canceler]struct{})
319 p.children[child] = struct{}{}
326 case <-parent.Done():
327 child.cancel(false, parent.Err(), Cause(parent))
334 // &cancelCtxKey is the key that a cancelCtx returns itself for.
337 // parentCancelCtx returns the underlying *cancelCtx for parent.
338 // It does this by looking up parent.Value(&cancelCtxKey) to find
339 // the innermost enclosing *cancelCtx and then checking whether
340 // parent.Done() matches that *cancelCtx. (If not, the *cancelCtx
341 // has been wrapped in a custom implementation providing a
342 // different done channel, in which case we should not bypass it.)
343 func parentCancelCtx(parent Context) (*cancelCtx, bool) {
344 done := parent.Done()
345 if done == closedchan || done == nil {
348 p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)
352 pdone, _ := p.done.Load().(chan struct{})
359 // removeChild removes a context from its parent.
360 func removeChild(parent Context, child canceler) {
361 p, ok := parentCancelCtx(parent)
366 if p.children != nil {
367 delete(p.children, child)
372 // A canceler is a context type that can be canceled directly. The
373 // implementations are *cancelCtx and *timerCtx.
374 type canceler interface {
375 cancel(removeFromParent bool, err, cause error)
376 Done() <-chan struct{}
379 // closedchan is a reusable closed channel.
380 var closedchan = make(chan struct{})
386 // A cancelCtx can be canceled. When canceled, it also cancels any children
387 // that implement canceler.
388 type cancelCtx struct {
391 mu sync.Mutex // protects following fields
392 done atomic.Value // of chan struct{}, created lazily, closed by first cancel call
393 children map[canceler]struct{} // set to nil by the first cancel call
394 err error // set to non-nil by the first cancel call
395 cause error // set to non-nil by the first cancel call
398 func (c *cancelCtx) Value(key any) any {
399 if key == &cancelCtxKey {
402 return value(c.Context, key)
405 func (c *cancelCtx) Done() <-chan struct{} {
408 return d.(chan struct{})
414 d = make(chan struct{})
417 return d.(chan struct{})
420 func (c *cancelCtx) Err() error {
427 type stringer interface {
431 func contextName(c Context) string {
432 if s, ok := c.(stringer); ok {
435 return reflectlite.TypeOf(c).String()
438 func (c *cancelCtx) String() string {
439 return contextName(c.Context) + ".WithCancel"
442 // cancel closes c.done, cancels each of c's children, and, if
443 // removeFromParent is true, removes c from its parent's children.
444 // cancel sets c.cause to cause if this is the first time c is canceled.
445 func (c *cancelCtx) cancel(removeFromParent bool, err, cause error) {
447 panic("context: internal error: missing cancel error")
455 return // already canceled
459 d, _ := c.done.Load().(chan struct{})
461 c.done.Store(closedchan)
465 for child := range c.children {
466 // NOTE: acquiring the child's lock while holding parent's lock.
467 child.cancel(false, err, cause)
472 if removeFromParent {
473 removeChild(c.Context, c)
477 // WithoutCancel returns a copy of parent that is not canceled when parent is canceled.
478 // The returned context returns no Deadline or Err, and its Done channel is nil.
479 // Calling Cause on the returned context returns nil.
480 func WithoutCancel(parent Context) Context {
482 panic("cannot create context from nil parent")
484 return withoutCancelCtx{parent}
487 type withoutCancelCtx struct {
491 func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool) {
495 func (withoutCancelCtx) Done() <-chan struct{} {
499 func (withoutCancelCtx) Err() error {
503 func (c withoutCancelCtx) Value(key any) any {
507 func (c withoutCancelCtx) String() string {
508 return contextName(c.c) + ".WithoutCancel"
511 // WithDeadline returns a copy of the parent context with the deadline adjusted
512 // to be no later than d. If the parent's deadline is already earlier than d,
513 // WithDeadline(parent, d) is semantically equivalent to parent. The returned
514 // context's Done channel is closed when the deadline expires, when the returned
515 // cancel function is called, or when the parent context's Done channel is
516 // closed, whichever happens first.
518 // Canceling this context releases resources associated with it, so code should
519 // call cancel as soon as the operations running in this Context complete.
520 func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
521 return WithDeadlineCause(parent, d, nil)
524 // WithDeadlineCause behaves like WithDeadline but also sets the cause of the
525 // returned Context when the deadline is exceeded. The returned CancelFunc does
526 // not set the cause.
527 func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc) {
529 panic("cannot create context from nil parent")
531 if cur, ok := parent.Deadline(); ok && cur.Before(d) {
532 // The current deadline is already sooner than the new one.
533 return WithCancel(parent)
536 cancelCtx: cancelCtx{Context: parent},
539 propagateCancel(parent, c)
542 c.cancel(true, DeadlineExceeded, cause) // deadline has already passed
543 return c, func() { c.cancel(false, Canceled, nil) }
548 c.timer = time.AfterFunc(dur, func() {
549 c.cancel(true, DeadlineExceeded, cause)
552 return c, func() { c.cancel(true, Canceled, nil) }
555 // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
556 // implement Done and Err. It implements cancel by stopping its timer then
557 // delegating to cancelCtx.cancel.
558 type timerCtx struct {
560 timer *time.Timer // Under cancelCtx.mu.
565 func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
566 return c.deadline, true
569 func (c *timerCtx) String() string {
570 return contextName(c.cancelCtx.Context) + ".WithDeadline(" +
571 c.deadline.String() + " [" +
572 time.Until(c.deadline).String() + "])"
575 func (c *timerCtx) cancel(removeFromParent bool, err, cause error) {
576 c.cancelCtx.cancel(false, err, cause)
577 if removeFromParent {
578 // Remove this timerCtx from its parent cancelCtx's children.
579 removeChild(c.cancelCtx.Context, c)
589 // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
591 // Canceling this context releases resources associated with it, so code should
592 // call cancel as soon as the operations running in this Context complete:
594 // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
595 // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
596 // defer cancel() // releases resources if slowOperation completes before timeout elapses
597 // return slowOperation(ctx)
599 func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
600 return WithDeadline(parent, time.Now().Add(timeout))
603 // WithTimeoutCause behaves like WithTimeout but also sets the cause of the
604 // returned Context when the timout expires. The returned CancelFunc does
605 // not set the cause.
606 func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc) {
607 return WithDeadlineCause(parent, time.Now().Add(timeout), cause)
610 // WithValue returns a copy of parent in which the value associated with key is
613 // Use context Values only for request-scoped data that transits processes and
614 // APIs, not for passing optional parameters to functions.
616 // The provided key must be comparable and should not be of type
617 // string or any other built-in type to avoid collisions between
618 // packages using context. Users of WithValue should define their own
619 // types for keys. To avoid allocating when assigning to an
620 // interface{}, context keys often have concrete type
621 // struct{}. Alternatively, exported context key variables' static
622 // type should be a pointer or interface.
623 func WithValue(parent Context, key, val any) Context {
625 panic("cannot create context from nil parent")
630 if !reflectlite.TypeOf(key).Comparable() {
631 panic("key is not comparable")
633 return &valueCtx{parent, key, val}
636 // A valueCtx carries a key-value pair. It implements Value for that key and
637 // delegates all other calls to the embedded Context.
638 type valueCtx struct {
643 // stringify tries a bit to stringify v, without using fmt, since we don't
644 // want context depending on the unicode tables. This is only used by
645 // *valueCtx.String().
646 func stringify(v any) string {
647 switch s := v.(type) {
653 return "<not Stringer>"
656 func (c *valueCtx) String() string {
657 return contextName(c.Context) + ".WithValue(type " +
658 reflectlite.TypeOf(c.key).String() +
659 ", val " + stringify(c.val) + ")"
662 func (c *valueCtx) Value(key any) any {
666 return value(c.Context, key)
669 func value(c Context, key any) any {
671 switch ctx := c.(type) {
678 if key == &cancelCtxKey {
682 case withoutCancelCtx:
683 if key == &cancelCtxKey {
684 // This implements Cause(ctx) == nil
685 // when ctx is created using WithoutCancel.
690 if key == &cancelCtxKey {
691 return &ctx.cancelCtx
694 case backgroundCtx, todoCtx: