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 // cancelation 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
58 // A Context carries a deadline, a cancelation 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.
72 // WithCancel arranges for Done to be closed when cancel is called;
73 // WithDeadline arranges for Done to be closed when the deadline
74 // expires; WithTimeout arranges for Done to be closed when the timeout
77 // Done is provided for use in select statements:
79 // // Stream generates values with DoSomething and sends them to out
80 // // until DoSomething returns an error or ctx.Done is closed.
81 // func Stream(ctx context.Context, out chan<- Value) error {
83 // v, err := DoSomething(ctx)
95 // See https://blog.golang.org/pipelines for more examples of how to use
96 // a Done channel for cancelation.
97 Done() <-chan struct{}
99 // If Done is not yet closed, Err returns nil.
100 // If Done is closed, Err returns a non-nil error explaining why:
101 // Canceled if the context was canceled
102 // or DeadlineExceeded if the context's deadline passed.
103 // After Err returns a non-nil error, successive calls to Err return the same error.
106 // Value returns the value associated with this context for key, or nil
107 // if no value is associated with key. Successive calls to Value with
108 // the same key returns the same result.
110 // Use context values only for request-scoped data that transits
111 // processes and API boundaries, not for passing optional parameters to
114 // A key identifies a specific value in a Context. Functions that wish
115 // to store values in Context typically allocate a key in a global
116 // variable then use that key as the argument to context.WithValue and
117 // Context.Value. A key can be any type that supports equality;
118 // packages should define keys as an unexported type to avoid
121 // Packages that define a Context key should provide type-safe accessors
122 // for the values stored using that key:
124 // // Package user defines a User type that's stored in Contexts.
129 // // User is the type of value stored in the Contexts.
130 // type User struct {...}
132 // // key is an unexported type for keys defined in this package.
133 // // This prevents collisions with keys defined in other packages.
136 // // userKey is the key for user.User values in Contexts. It is
137 // // unexported; clients use user.NewContext and user.FromContext
138 // // instead of using this key directly.
141 // // NewContext returns a new Context that carries value u.
142 // func NewContext(ctx context.Context, u *User) context.Context {
143 // return context.WithValue(ctx, userKey, u)
146 // // FromContext returns the User value stored in ctx, if any.
147 // func FromContext(ctx context.Context) (*User, bool) {
148 // u, ok := ctx.Value(userKey).(*User)
151 Value(key
interface{}) interface{}
154 // Canceled is the error returned by Context.Err when the context is canceled.
155 var Canceled
= errors
.New("context canceled")
157 // DeadlineExceeded is the error returned by Context.Err when the context's
159 var DeadlineExceeded error
= deadlineExceededError
{}
161 type deadlineExceededError
struct{}
163 func (deadlineExceededError
) Error() string { return "context deadline exceeded" }
164 func (deadlineExceededError
) Timeout() bool { return true }
165 func (deadlineExceededError
) Temporary() bool { return true }
167 // An emptyCtx is never canceled, has no values, and has no deadline. It is not
168 // struct{}, since vars of this type must have distinct addresses.
171 func (*emptyCtx
) Deadline() (deadline time
.Time
, ok
bool) {
175 func (*emptyCtx
) Done() <-chan struct{} {
179 func (*emptyCtx
) Err() error
{
183 func (*emptyCtx
) Value(key
interface{}) interface{} {
187 func (e
*emptyCtx
) String() string {
190 return "context.Background"
192 return "context.TODO"
194 return "unknown empty Context"
198 background
= new(emptyCtx
)
202 // Background returns a non-nil, empty Context. It is never canceled, has no
203 // values, and has no deadline. It is typically used by the main function,
204 // initialization, and tests, and as the top-level Context for incoming
206 func Background() Context
{
210 // TODO returns a non-nil, empty Context. Code should use context.TODO when
211 // it's unclear which Context to use or it is not yet available (because the
212 // surrounding function has not yet been extended to accept a Context
213 // parameter). TODO is recognized by static analysis tools that determine
214 // whether Contexts are propagated correctly in a program.
215 func TODO() Context
{
219 // A CancelFunc tells an operation to abandon its work.
220 // A CancelFunc does not wait for the work to stop.
221 // After the first call, subsequent calls to a CancelFunc do nothing.
222 type CancelFunc
func()
224 // WithCancel returns a copy of parent with a new Done channel. The returned
225 // context's Done channel is closed when the returned cancel function is called
226 // or when the parent context's Done channel is closed, whichever happens first.
228 // Canceling this context releases resources associated with it, so code should
229 // call cancel as soon as the operations running in this Context complete.
230 func WithCancel(parent Context
) (ctx Context
, cancel CancelFunc
) {
231 c
:= newCancelCtx(parent
)
232 propagateCancel(parent
, &c
)
233 return &c
, func() { c
.cancel(true, Canceled
) }
236 // newCancelCtx returns an initialized cancelCtx.
237 func newCancelCtx(parent Context
) cancelCtx
{
238 return cancelCtx
{Context
: parent
}
241 // propagateCancel arranges for child to be canceled when parent is.
242 func propagateCancel(parent Context
, child canceler
) {
243 if parent
.Done() == nil {
244 return // parent is never canceled
246 if p
, ok
:= parentCancelCtx(parent
); ok
{
249 // parent has already been canceled
250 child
.cancel(false, p
.err
)
252 if p
.children
== nil {
253 p
.children
= make(map[canceler
]struct{})
255 p
.children
[child
] = struct{}{}
261 case <-parent
.Done():
262 child
.cancel(false, parent
.Err())
269 // parentCancelCtx follows a chain of parent references until it finds a
270 // *cancelCtx. This function understands how each of the concrete types in this
271 // package represents its parent.
272 func parentCancelCtx(parent Context
) (*cancelCtx
, bool) {
274 switch c
:= parent
.(type) {
278 return &c
.cancelCtx
, true
287 // removeChild removes a context from its parent.
288 func removeChild(parent Context
, child canceler
) {
289 p
, ok
:= parentCancelCtx(parent
)
294 if p
.children
!= nil {
295 delete(p
.children
, child
)
300 // A canceler is a context type that can be canceled directly. The
301 // implementations are *cancelCtx and *timerCtx.
302 type canceler
interface {
303 cancel(removeFromParent
bool, err error
)
304 Done() <-chan struct{}
307 // closedchan is a reusable closed channel.
308 var closedchan
= make(chan struct{})
314 // A cancelCtx can be canceled. When canceled, it also cancels any children
315 // that implement canceler.
316 type cancelCtx
struct {
319 mu sync
.Mutex
// protects following fields
320 done
chan struct{} // created lazily, closed by first cancel call
321 children
map[canceler
]struct{} // set to nil by the first cancel call
322 err error
// set to non-nil by the first cancel call
325 func (c
*cancelCtx
) Done() <-chan struct{} {
328 c
.done
= make(chan struct{})
335 func (c
*cancelCtx
) Err() error
{
342 func (c
*cancelCtx
) String() string {
343 return fmt
.Sprintf("%v.WithCancel", c
.Context
)
346 // cancel closes c.done, cancels each of c's children, and, if
347 // removeFromParent is true, removes c from its parent's children.
348 func (c
*cancelCtx
) cancel(removeFromParent
bool, err error
) {
350 panic("context: internal error: missing cancel error")
355 return // already canceled
363 for child
:= range c
.children
{
364 // NOTE: acquiring the child's lock while holding parent's lock.
365 child
.cancel(false, err
)
370 if removeFromParent
{
371 removeChild(c
.Context
, c
)
375 // WithDeadline returns a copy of the parent context with the deadline adjusted
376 // to be no later than d. If the parent's deadline is already earlier than d,
377 // WithDeadline(parent, d) is semantically equivalent to parent. The returned
378 // context's Done channel is closed when the deadline expires, when the returned
379 // cancel function is called, or when the parent context's Done channel is
380 // closed, whichever happens first.
382 // Canceling this context releases resources associated with it, so code should
383 // call cancel as soon as the operations running in this Context complete.
384 func WithDeadline(parent Context
, d time
.Time
) (Context
, CancelFunc
) {
385 if cur
, ok
:= parent
.Deadline(); ok
&& cur
.Before(d
) {
386 // The current deadline is already sooner than the new one.
387 return WithCancel(parent
)
390 cancelCtx
: newCancelCtx(parent
),
393 propagateCancel(parent
, c
)
396 c
.cancel(true, DeadlineExceeded
) // deadline has already passed
397 return c
, func() { c
.cancel(true, Canceled
) }
402 c
.timer
= time
.AfterFunc(dur
, func() {
403 c
.cancel(true, DeadlineExceeded
)
406 return c
, func() { c
.cancel(true, Canceled
) }
409 // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
410 // implement Done and Err. It implements cancel by stopping its timer then
411 // delegating to cancelCtx.cancel.
412 type timerCtx
struct {
414 timer
*time
.Timer
// Under cancelCtx.mu.
419 func (c
*timerCtx
) Deadline() (deadline time
.Time
, ok
bool) {
420 return c
.deadline
, true
423 func (c
*timerCtx
) String() string {
424 return fmt
.Sprintf("%v.WithDeadline(%s [%s])", c
.cancelCtx
.Context
, c
.deadline
, time
.Until(c
.deadline
))
427 func (c
*timerCtx
) cancel(removeFromParent
bool, err error
) {
428 c
.cancelCtx
.cancel(false, err
)
429 if removeFromParent
{
430 // Remove this timerCtx from its parent cancelCtx's children.
431 removeChild(c
.cancelCtx
.Context
, c
)
441 // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
443 // Canceling this context releases resources associated with it, so code should
444 // call cancel as soon as the operations running in this Context complete:
446 // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
447 // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
448 // defer cancel() // releases resources if slowOperation completes before timeout elapses
449 // return slowOperation(ctx)
451 func WithTimeout(parent Context
, timeout time
.Duration
) (Context
, CancelFunc
) {
452 return WithDeadline(parent
, time
.Now().Add(timeout
))
455 // WithValue returns a copy of parent in which the value associated with key is
458 // Use context Values only for request-scoped data that transits processes and
459 // APIs, not for passing optional parameters to functions.
461 // The provided key must be comparable and should not be of type
462 // string or any other built-in type to avoid collisions between
463 // packages using context. Users of WithValue should define their own
464 // types for keys. To avoid allocating when assigning to an
465 // interface{}, context keys often have concrete type
466 // struct{}. Alternatively, exported context key variables' static
467 // type should be a pointer or interface.
468 func WithValue(parent Context
, key
, val
interface{}) Context
{
472 if !reflect
.TypeOf(key
).Comparable() {
473 panic("key is not comparable")
475 return &valueCtx
{parent
, key
, val
}
478 // A valueCtx carries a key-value pair. It implements Value for that key and
479 // delegates all other calls to the embedded Context.
480 type valueCtx
struct {
485 func (c
*valueCtx
) String() string {
486 return fmt
.Sprintf("%v.WithValue(%#v, %#v)", c
.Context
, c
.key
, c
.val
)
489 func (c
*valueCtx
) Value(key
interface{}) interface{} {
493 return c
.Context
.Value(key
)