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 // Programs that use Contexts should follow these rules to keep interfaces
26 // consistent across packages and enable static analysis tools to check context
29 // Do not store Contexts inside a struct type; instead, pass a Context
30 // explicitly to each function that needs it. The Context should be the first
31 // parameter, typically named ctx:
33 // func DoSomething(ctx context.Context, arg Arg) error {
37 // Do not pass a nil Context, even if a function permits it. Pass context.TODO
38 // if you are unsure about which Context to use.
40 // Use context Values only for request-scoped data that transits processes and
41 // APIs, not for passing optional parameters to functions.
43 // The same Context may be passed to functions running in different goroutines;
44 // Contexts are safe for simultaneous use by multiple goroutines.
46 // See https://blog.golang.org/context for example code for a server that uses
52 "internal/reflectlite"
58 // A Context carries a deadline, a cancellation signal, and other values across
61 // Context's methods may be called by multiple goroutines simultaneously.
62 type Context
interface {
63 // Deadline returns the time when work done on behalf of this context
64 // should be canceled. Deadline returns ok==false when no deadline is
65 // set. Successive calls to Deadline return the same results.
66 Deadline() (deadline time
.Time
, ok
bool)
68 // Done returns a channel that's closed when work done on behalf of this
69 // context should be canceled. Done may return nil if this context can
70 // never be canceled. Successive calls to Done return the same value.
71 // The close of the Done channel may happen asynchronously,
72 // after the cancel function returns.
74 // WithCancel arranges for Done to be closed when cancel is called;
75 // WithDeadline arranges for Done to be closed when the deadline
76 // expires; WithTimeout arranges for Done to be closed when the timeout
79 // Done is provided for use in select statements:
81 // // Stream generates values with DoSomething and sends them to out
82 // // until DoSomething returns an error or ctx.Done is closed.
83 // func Stream(ctx context.Context, out chan<- Value) error {
85 // v, err := DoSomething(ctx)
97 // See https://blog.golang.org/pipelines for more examples of how to use
98 // a Done channel for cancellation.
99 Done() <-chan struct{}
101 // If Done is not yet closed, Err returns nil.
102 // If Done is closed, Err returns a non-nil error explaining why:
103 // Canceled if the context was canceled
104 // or DeadlineExceeded if the context's deadline passed.
105 // After Err returns a non-nil error, successive calls to Err return the same error.
108 // Value returns the value associated with this context for key, or nil
109 // if no value is associated with key. Successive calls to Value with
110 // the same key returns the same result.
112 // Use context values only for request-scoped data that transits
113 // processes and API boundaries, not for passing optional parameters to
116 // A key identifies a specific value in a Context. Functions that wish
117 // to store values in Context typically allocate a key in a global
118 // variable then use that key as the argument to context.WithValue and
119 // Context.Value. A key can be any type that supports equality;
120 // packages should define keys as an unexported type to avoid
123 // Packages that define a Context key should provide type-safe accessors
124 // for the values stored using that key:
126 // // Package user defines a User type that's stored in Contexts.
131 // // User is the type of value stored in the Contexts.
132 // type User struct {...}
134 // // key is an unexported type for keys defined in this package.
135 // // This prevents collisions with keys defined in other packages.
138 // // userKey is the key for user.User values in Contexts. It is
139 // // unexported; clients use user.NewContext and user.FromContext
140 // // instead of using this key directly.
143 // // NewContext returns a new Context that carries value u.
144 // func NewContext(ctx context.Context, u *User) context.Context {
145 // return context.WithValue(ctx, userKey, u)
148 // // FromContext returns the User value stored in ctx, if any.
149 // func FromContext(ctx context.Context) (*User, bool) {
150 // u, ok := ctx.Value(userKey).(*User)
156 // Canceled is the error returned by Context.Err when the context is canceled.
157 var Canceled
= errors
.New("context canceled")
159 // DeadlineExceeded is the error returned by Context.Err when the context's
161 var DeadlineExceeded error
= deadlineExceededError
{}
163 type deadlineExceededError
struct{}
165 func (deadlineExceededError
) Error() string { return "context deadline exceeded" }
166 func (deadlineExceededError
) Timeout() bool { return true }
167 func (deadlineExceededError
) Temporary() bool { return true }
169 // An emptyCtx is never canceled, has no values, and has no deadline. It is not
170 // struct{}, since vars of this type must have distinct addresses.
173 func (*emptyCtx
) Deadline() (deadline time
.Time
, ok
bool) {
177 func (*emptyCtx
) Done() <-chan struct{} {
181 func (*emptyCtx
) Err() error
{
185 func (*emptyCtx
) Value(key any
) any
{
189 func (e
*emptyCtx
) String() string {
192 return "context.Background"
194 return "context.TODO"
196 return "unknown empty Context"
200 background
= new(emptyCtx
)
204 // Background returns a non-nil, empty Context. It is never canceled, has no
205 // values, and has no deadline. It is typically used by the main function,
206 // initialization, and tests, and as the top-level Context for incoming
208 func Background() Context
{
212 // TODO returns a non-nil, empty Context. Code should use context.TODO when
213 // it's unclear which Context to use or it is not yet available (because the
214 // surrounding function has not yet been extended to accept a Context
216 func TODO() Context
{
220 // A CancelFunc tells an operation to abandon its work.
221 // A CancelFunc does not wait for the work to stop.
222 // A CancelFunc may be called by multiple goroutines simultaneously.
223 // After the first call, subsequent calls to a CancelFunc do nothing.
224 type CancelFunc
func()
226 // WithCancel returns a copy of parent with a new Done channel. The returned
227 // context's Done channel is closed when the returned cancel function is called
228 // or when the parent context's Done channel is closed, whichever happens first.
230 // Canceling this context releases resources associated with it, so code should
231 // call cancel as soon as the operations running in this Context complete.
232 func WithCancel(parent Context
) (ctx Context
, cancel CancelFunc
) {
234 panic("cannot create context from nil parent")
236 c
:= newCancelCtx(parent
)
237 propagateCancel(parent
, &c
)
238 return &c
, func() { c
.cancel(true, Canceled
) }
241 // newCancelCtx returns an initialized cancelCtx.
242 func newCancelCtx(parent Context
) cancelCtx
{
243 return cancelCtx
{Context
: parent
}
246 // goroutines counts the number of goroutines ever created; for testing.
249 // propagateCancel arranges for child to be canceled when parent is.
250 func propagateCancel(parent Context
, child canceler
) {
251 done
:= parent
.Done()
253 return // parent is never canceled
258 // parent is already canceled
259 child
.cancel(false, parent
.Err())
264 if p
, ok
:= parentCancelCtx(parent
); ok
{
267 // parent has already been canceled
268 child
.cancel(false, p
.err
)
270 if p
.children
== nil {
271 p
.children
= make(map[canceler
]struct{})
273 p
.children
[child
] = struct{}{}
277 atomic
.AddInt32(&goroutines
, +1)
280 case <-parent
.Done():
281 child
.cancel(false, parent
.Err())
288 // &cancelCtxKey is the key that a cancelCtx returns itself for.
291 // parentCancelCtx returns the underlying *cancelCtx for parent.
292 // It does this by looking up parent.Value(&cancelCtxKey) to find
293 // the innermost enclosing *cancelCtx and then checking whether
294 // parent.Done() matches that *cancelCtx. (If not, the *cancelCtx
295 // has been wrapped in a custom implementation providing a
296 // different done channel, in which case we should not bypass it.)
297 func parentCancelCtx(parent Context
) (*cancelCtx
, bool) {
298 done
:= parent
.Done()
299 if done
== closedchan || done
== nil {
302 p
, ok
:= parent
.Value(&cancelCtxKey
).(*cancelCtx
)
306 pdone
, _
:= p
.done
.Load().(chan struct{})
313 // removeChild removes a context from its parent.
314 func removeChild(parent Context
, child canceler
) {
315 p
, ok
:= parentCancelCtx(parent
)
320 if p
.children
!= nil {
321 delete(p
.children
, child
)
326 // A canceler is a context type that can be canceled directly. The
327 // implementations are *cancelCtx and *timerCtx.
328 type canceler
interface {
329 cancel(removeFromParent
bool, err error
)
330 Done() <-chan struct{}
333 // closedchan is a reusable closed channel.
334 var closedchan
= make(chan struct{})
340 // A cancelCtx can be canceled. When canceled, it also cancels any children
341 // that implement canceler.
342 type cancelCtx
struct {
345 mu sync
.Mutex
// protects following fields
346 done atomic
.Value
// of chan struct{}, created lazily, closed by first cancel call
347 children
map[canceler
]struct{} // set to nil by the first cancel call
348 err error
// set to non-nil by the first cancel call
351 func (c
*cancelCtx
) Value(key any
) any
{
352 if key
== &cancelCtxKey
{
355 return value(c
.Context
, key
)
358 func (c
*cancelCtx
) Done() <-chan struct{} {
361 return d
.(chan struct{})
367 d
= make(chan struct{})
370 return d
.(chan struct{})
373 func (c
*cancelCtx
) Err() error
{
380 type stringer
interface {
384 func contextName(c Context
) string {
385 if s
, ok
:= c
.(stringer
); ok
{
388 return reflectlite
.TypeOf(c
).String()
391 func (c
*cancelCtx
) String() string {
392 return contextName(c
.Context
) + ".WithCancel"
395 // cancel closes c.done, cancels each of c's children, and, if
396 // removeFromParent is true, removes c from its parent's children.
397 func (c
*cancelCtx
) cancel(removeFromParent
bool, err error
) {
399 panic("context: internal error: missing cancel error")
404 return // already canceled
407 d
, _
:= c
.done
.Load().(chan struct{})
409 c
.done
.Store(closedchan
)
413 for child
:= range c
.children
{
414 // NOTE: acquiring the child's lock while holding parent's lock.
415 child
.cancel(false, err
)
420 if removeFromParent
{
421 removeChild(c
.Context
, c
)
425 // WithDeadline returns a copy of the parent context with the deadline adjusted
426 // to be no later than d. If the parent's deadline is already earlier than d,
427 // WithDeadline(parent, d) is semantically equivalent to parent. The returned
428 // context's Done channel is closed when the deadline expires, when the returned
429 // cancel function is called, or when the parent context's Done channel is
430 // closed, whichever happens first.
432 // Canceling this context releases resources associated with it, so code should
433 // call cancel as soon as the operations running in this Context complete.
434 func WithDeadline(parent Context
, d time
.Time
) (Context
, CancelFunc
) {
436 panic("cannot create context from nil parent")
438 if cur
, ok
:= parent
.Deadline(); ok
&& cur
.Before(d
) {
439 // The current deadline is already sooner than the new one.
440 return WithCancel(parent
)
443 cancelCtx
: newCancelCtx(parent
),
446 propagateCancel(parent
, c
)
449 c
.cancel(true, DeadlineExceeded
) // deadline has already passed
450 return c
, func() { c
.cancel(false, Canceled
) }
455 c
.timer
= time
.AfterFunc(dur
, func() {
456 c
.cancel(true, DeadlineExceeded
)
459 return c
, func() { c
.cancel(true, Canceled
) }
462 // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
463 // implement Done and Err. It implements cancel by stopping its timer then
464 // delegating to cancelCtx.cancel.
465 type timerCtx
struct {
467 timer
*time
.Timer
// Under cancelCtx.mu.
472 func (c
*timerCtx
) Deadline() (deadline time
.Time
, ok
bool) {
473 return c
.deadline
, true
476 func (c
*timerCtx
) String() string {
477 return contextName(c
.cancelCtx
.Context
) + ".WithDeadline(" +
478 c
.deadline
.String() + " [" +
479 time
.Until(c
.deadline
).String() + "])"
482 func (c
*timerCtx
) cancel(removeFromParent
bool, err error
) {
483 c
.cancelCtx
.cancel(false, err
)
484 if removeFromParent
{
485 // Remove this timerCtx from its parent cancelCtx's children.
486 removeChild(c
.cancelCtx
.Context
, c
)
496 // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
498 // Canceling this context releases resources associated with it, so code should
499 // call cancel as soon as the operations running in this Context complete:
501 // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
502 // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
503 // defer cancel() // releases resources if slowOperation completes before timeout elapses
504 // return slowOperation(ctx)
506 func WithTimeout(parent Context
, timeout time
.Duration
) (Context
, CancelFunc
) {
507 return WithDeadline(parent
, time
.Now().Add(timeout
))
510 // WithValue returns a copy of parent in which the value associated with key is
513 // Use context Values only for request-scoped data that transits processes and
514 // APIs, not for passing optional parameters to functions.
516 // The provided key must be comparable and should not be of type
517 // string or any other built-in type to avoid collisions between
518 // packages using context. Users of WithValue should define their own
519 // types for keys. To avoid allocating when assigning to an
520 // interface{}, context keys often have concrete type
521 // struct{}. Alternatively, exported context key variables' static
522 // type should be a pointer or interface.
523 func WithValue(parent Context
, key
, val any
) Context
{
525 panic("cannot create context from nil parent")
530 if !reflectlite
.TypeOf(key
).Comparable() {
531 panic("key is not comparable")
533 return &valueCtx
{parent
, key
, val
}
536 // A valueCtx carries a key-value pair. It implements Value for that key and
537 // delegates all other calls to the embedded Context.
538 type valueCtx
struct {
543 // stringify tries a bit to stringify v, without using fmt, since we don't
544 // want context depending on the unicode tables. This is only used by
545 // *valueCtx.String().
546 func stringify(v any
) string {
547 switch s
:= v
.(type) {
553 return "<not Stringer>"
556 func (c
*valueCtx
) String() string {
557 return contextName(c
.Context
) + ".WithValue(type " +
558 reflectlite
.TypeOf(c
.key
).String() +
559 ", val " + stringify(c
.val
) + ")"
562 func (c
*valueCtx
) Value(key any
) any
{
566 return value(c
.Context
, key
)
569 func value(c Context
, key any
) any
{
571 switch ctx
:= c
.(type) {
578 if key
== &cancelCtxKey
{
583 if key
== &cancelCtxKey
{
584 return &ctx
.cancelCtx