Source file src/context/context.go

Documentation: context

     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  
     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.
     8  //
     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.
    15  //
    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.
    24  //
    25  // Programs that use Contexts should follow these rules to keep interfaces
    26  // consistent across packages and enable static analysis tools to check context
    27  // propagation:
    28  //
    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:
    32  //
    33  // 	func DoSomething(ctx context.Context, arg Arg) error {
    34  // 		// ... use ctx ...
    35  // 	}
    36  //
    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.
    39  //
    40  // Use context Values only for request-scoped data that transits processes and
    41  // APIs, not for passing optional parameters to functions.
    42  //
    43  // The same Context may be passed to functions running in different goroutines;
    44  // Contexts are safe for simultaneous use by multiple goroutines.
    45  //
    46  // See https://blog.golang.org/context for example code for a server that uses
    47  // Contexts.
    48  package context
    49  
    50  import (
    51  	"errors"
    52  	"internal/reflectlite"
    53  	"sync"
    54  	"sync/atomic"
    55  	"time"
    56  )
    57  
    58  // A Context carries a deadline, a cancellation signal, and other values across
    59  // API boundaries.
    60  //
    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)
    67  
    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.
    73  	//
    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
    77  	// elapses.
    78  	//
    79  	// Done is provided for use in select statements:
    80  	//
    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 {
    84  	//  	for {
    85  	//  		v, err := DoSomething(ctx)
    86  	//  		if err != nil {
    87  	//  			return err
    88  	//  		}
    89  	//  		select {
    90  	//  		case <-ctx.Done():
    91  	//  			return ctx.Err()
    92  	//  		case out <- v:
    93  	//  		}
    94  	//  	}
    95  	//  }
    96  	//
    97  	// See https://blog.golang.org/pipelines for more examples of how to use
    98  	// a Done channel for cancellation.
    99  	Done() <-chan struct{}
   100  
   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.
   106  	Err() error
   107  
   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.
   111  	//
   112  	// Use context values only for request-scoped data that transits
   113  	// processes and API boundaries, not for passing optional parameters to
   114  	// functions.
   115  	//
   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
   121  	// collisions.
   122  	//
   123  	// Packages that define a Context key should provide type-safe accessors
   124  	// for the values stored using that key:
   125  	//
   126  	// 	// Package user defines a User type that's stored in Contexts.
   127  	// 	package user
   128  	//
   129  	// 	import "context"
   130  	//
   131  	// 	// User is the type of value stored in the Contexts.
   132  	// 	type User struct {...}
   133  	//
   134  	// 	// key is an unexported type for keys defined in this package.
   135  	// 	// This prevents collisions with keys defined in other packages.
   136  	// 	type key int
   137  	//
   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.
   141  	// 	var userKey key
   142  	//
   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)
   146  	// 	}
   147  	//
   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)
   151  	// 		return u, ok
   152  	// 	}
   153  	Value(key interface{}) interface{}
   154  }
   155  
   156  // Canceled is the error returned by Context.Err when the context is canceled.
   157  var Canceled = errors.New("context canceled")
   158  
   159  // DeadlineExceeded is the error returned by Context.Err when the context's
   160  // deadline passes.
   161  var DeadlineExceeded error = deadlineExceededError{}
   162  
   163  type deadlineExceededError struct{}
   164  
   165  func (deadlineExceededError) Error() string   { return "context deadline exceeded" }
   166  func (deadlineExceededError) Timeout() bool   { return true }
   167  func (deadlineExceededError) Temporary() bool { return true }
   168  
   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.
   171  type emptyCtx int
   172  
   173  func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
   174  	return
   175  }
   176  
   177  func (*emptyCtx) Done() <-chan struct{} {
   178  	return nil
   179  }
   180  
   181  func (*emptyCtx) Err() error {
   182  	return nil
   183  }
   184  
   185  func (*emptyCtx) Value(key interface{}) interface{} {
   186  	return nil
   187  }
   188  
   189  func (e *emptyCtx) String() string {
   190  	switch e {
   191  	case background:
   192  		return "context.Background"
   193  	case todo:
   194  		return "context.TODO"
   195  	}
   196  	return "unknown empty Context"
   197  }
   198  
   199  var (
   200  	background = new(emptyCtx)
   201  	todo       = new(emptyCtx)
   202  )
   203  
   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
   207  // requests.
   208  func Background() Context {
   209  	return background
   210  }
   211  
   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
   215  // parameter).
   216  func TODO() Context {
   217  	return todo
   218  }
   219  
   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()
   225  
   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.
   229  //
   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) {
   233  	c := newCancelCtx(parent)
   234  	propagateCancel(parent, &c)
   235  	return &c, func() { c.cancel(true, Canceled) }
   236  }
   237  
   238  // newCancelCtx returns an initialized cancelCtx.
   239  func newCancelCtx(parent Context) cancelCtx {
   240  	return cancelCtx{Context: parent}
   241  }
   242  
   243  // goroutines counts the number of goroutines ever created; for testing.
   244  var goroutines int32
   245  
   246  // propagateCancel arranges for child to be canceled when parent is.
   247  func propagateCancel(parent Context, child canceler) {
   248  	done := parent.Done()
   249  	if done == nil {
   250  		return // parent is never canceled
   251  	}
   252  
   253  	select {
   254  	case <-done:
   255  		// parent is already canceled
   256  		child.cancel(false, parent.Err())
   257  		return
   258  	default:
   259  	}
   260  
   261  	if p, ok := parentCancelCtx(parent); ok {
   262  		p.mu.Lock()
   263  		if p.err != nil {
   264  			// parent has already been canceled
   265  			child.cancel(false, p.err)
   266  		} else {
   267  			if p.children == nil {
   268  				p.children = make(map[canceler]struct{})
   269  			}
   270  			p.children[child] = struct{}{}
   271  		}
   272  		p.mu.Unlock()
   273  	} else {
   274  		atomic.AddInt32(&goroutines, +1)
   275  		go func() {
   276  			select {
   277  			case <-parent.Done():
   278  				child.cancel(false, parent.Err())
   279  			case <-child.Done():
   280  			}
   281  		}()
   282  	}
   283  }
   284  
   285  // &cancelCtxKey is the key that a cancelCtx returns itself for.
   286  var cancelCtxKey int
   287  
   288  // parentCancelCtx returns the underlying *cancelCtx for parent.
   289  // It does this by looking up parent.Value(&cancelCtxKey) to find
   290  // the innermost enclosing *cancelCtx and then checking whether
   291  // parent.Done() matches that *cancelCtx. (If not, the *cancelCtx
   292  // has been wrapped in a custom implementation providing a
   293  // different done channel, in which case we should not bypass it.)
   294  func parentCancelCtx(parent Context) (*cancelCtx, bool) {
   295  	done := parent.Done()
   296  	if done == closedchan || done == nil {
   297  		return nil, false
   298  	}
   299  	p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)
   300  	if !ok {
   301  		return nil, false
   302  	}
   303  	p.mu.Lock()
   304  	ok = p.done == done
   305  	p.mu.Unlock()
   306  	if !ok {
   307  		return nil, false
   308  	}
   309  	return p, true
   310  }
   311  
   312  // removeChild removes a context from its parent.
   313  func removeChild(parent Context, child canceler) {
   314  	p, ok := parentCancelCtx(parent)
   315  	if !ok {
   316  		return
   317  	}
   318  	p.mu.Lock()
   319  	if p.children != nil {
   320  		delete(p.children, child)
   321  	}
   322  	p.mu.Unlock()
   323  }
   324  
   325  // A canceler is a context type that can be canceled directly. The
   326  // implementations are *cancelCtx and *timerCtx.
   327  type canceler interface {
   328  	cancel(removeFromParent bool, err error)
   329  	Done() <-chan struct{}
   330  }
   331  
   332  // closedchan is a reusable closed channel.
   333  var closedchan = make(chan struct{})
   334  
   335  func init() {
   336  	close(closedchan)
   337  }
   338  
   339  // A cancelCtx can be canceled. When canceled, it also cancels any children
   340  // that implement canceler.
   341  type cancelCtx struct {
   342  	Context
   343  
   344  	mu       sync.Mutex            // protects following fields
   345  	done     chan struct{}         // created lazily, closed by first cancel call
   346  	children map[canceler]struct{} // set to nil by the first cancel call
   347  	err      error                 // set to non-nil by the first cancel call
   348  }
   349  
   350  func (c *cancelCtx) Value(key interface{}) interface{} {
   351  	if key == &cancelCtxKey {
   352  		return c
   353  	}
   354  	return c.Context.Value(key)
   355  }
   356  
   357  func (c *cancelCtx) Done() <-chan struct{} {
   358  	c.mu.Lock()
   359  	if c.done == nil {
   360  		c.done = make(chan struct{})
   361  	}
   362  	d := c.done
   363  	c.mu.Unlock()
   364  	return d
   365  }
   366  
   367  func (c *cancelCtx) Err() error {
   368  	c.mu.Lock()
   369  	err := c.err
   370  	c.mu.Unlock()
   371  	return err
   372  }
   373  
   374  type stringer interface {
   375  	String() string
   376  }
   377  
   378  func contextName(c Context) string {
   379  	if s, ok := c.(stringer); ok {
   380  		return s.String()
   381  	}
   382  	return reflectlite.TypeOf(c).String()
   383  }
   384  
   385  func (c *cancelCtx) String() string {
   386  	return contextName(c.Context) + ".WithCancel"
   387  }
   388  
   389  // cancel closes c.done, cancels each of c's children, and, if
   390  // removeFromParent is true, removes c from its parent's children.
   391  func (c *cancelCtx) cancel(removeFromParent bool, err error) {
   392  	if err == nil {
   393  		panic("context: internal error: missing cancel error")
   394  	}
   395  	c.mu.Lock()
   396  	if c.err != nil {
   397  		c.mu.Unlock()
   398  		return // already canceled
   399  	}
   400  	c.err = err
   401  	if c.done == nil {
   402  		c.done = closedchan
   403  	} else {
   404  		close(c.done)
   405  	}
   406  	for child := range c.children {
   407  		// NOTE: acquiring the child's lock while holding parent's lock.
   408  		child.cancel(false, err)
   409  	}
   410  	c.children = nil
   411  	c.mu.Unlock()
   412  
   413  	if removeFromParent {
   414  		removeChild(c.Context, c)
   415  	}
   416  }
   417  
   418  // WithDeadline returns a copy of the parent context with the deadline adjusted
   419  // to be no later than d. If the parent's deadline is already earlier than d,
   420  // WithDeadline(parent, d) is semantically equivalent to parent. The returned
   421  // context's Done channel is closed when the deadline expires, when the returned
   422  // cancel function is called, or when the parent context's Done channel is
   423  // closed, whichever happens first.
   424  //
   425  // Canceling this context releases resources associated with it, so code should
   426  // call cancel as soon as the operations running in this Context complete.
   427  func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
   428  	if cur, ok := parent.Deadline(); ok && cur.Before(d) {
   429  		// The current deadline is already sooner than the new one.
   430  		return WithCancel(parent)
   431  	}
   432  	c := &timerCtx{
   433  		cancelCtx: newCancelCtx(parent),
   434  		deadline:  d,
   435  	}
   436  	propagateCancel(parent, c)
   437  	dur := time.Until(d)
   438  	if dur <= 0 {
   439  		c.cancel(true, DeadlineExceeded) // deadline has already passed
   440  		return c, func() { c.cancel(false, Canceled) }
   441  	}
   442  	c.mu.Lock()
   443  	defer c.mu.Unlock()
   444  	if c.err == nil {
   445  		c.timer = time.AfterFunc(dur, func() {
   446  			c.cancel(true, DeadlineExceeded)
   447  		})
   448  	}
   449  	return c, func() { c.cancel(true, Canceled) }
   450  }
   451  
   452  // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
   453  // implement Done and Err. It implements cancel by stopping its timer then
   454  // delegating to cancelCtx.cancel.
   455  type timerCtx struct {
   456  	cancelCtx
   457  	timer *time.Timer // Under cancelCtx.mu.
   458  
   459  	deadline time.Time
   460  }
   461  
   462  func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
   463  	return c.deadline, true
   464  }
   465  
   466  func (c *timerCtx) String() string {
   467  	return contextName(c.cancelCtx.Context) + ".WithDeadline(" +
   468  		c.deadline.String() + " [" +
   469  		time.Until(c.deadline).String() + "])"
   470  }
   471  
   472  func (c *timerCtx) cancel(removeFromParent bool, err error) {
   473  	c.cancelCtx.cancel(false, err)
   474  	if removeFromParent {
   475  		// Remove this timerCtx from its parent cancelCtx's children.
   476  		removeChild(c.cancelCtx.Context, c)
   477  	}
   478  	c.mu.Lock()
   479  	if c.timer != nil {
   480  		c.timer.Stop()
   481  		c.timer = nil
   482  	}
   483  	c.mu.Unlock()
   484  }
   485  
   486  // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
   487  //
   488  // Canceling this context releases resources associated with it, so code should
   489  // call cancel as soon as the operations running in this Context complete:
   490  //
   491  // 	func slowOperationWithTimeout(ctx context.Context) (Result, error) {
   492  // 		ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
   493  // 		defer cancel()  // releases resources if slowOperation completes before timeout elapses
   494  // 		return slowOperation(ctx)
   495  // 	}
   496  func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
   497  	return WithDeadline(parent, time.Now().Add(timeout))
   498  }
   499  
   500  // WithValue returns a copy of parent in which the value associated with key is
   501  // val.
   502  //
   503  // Use context Values only for request-scoped data that transits processes and
   504  // APIs, not for passing optional parameters to functions.
   505  //
   506  // The provided key must be comparable and should not be of type
   507  // string or any other built-in type to avoid collisions between
   508  // packages using context. Users of WithValue should define their own
   509  // types for keys. To avoid allocating when assigning to an
   510  // interface{}, context keys often have concrete type
   511  // struct{}. Alternatively, exported context key variables' static
   512  // type should be a pointer or interface.
   513  func WithValue(parent Context, key, val interface{}) Context {
   514  	if key == nil {
   515  		panic("nil key")
   516  	}
   517  	if !reflectlite.TypeOf(key).Comparable() {
   518  		panic("key is not comparable")
   519  	}
   520  	return &valueCtx{parent, key, val}
   521  }
   522  
   523  // A valueCtx carries a key-value pair. It implements Value for that key and
   524  // delegates all other calls to the embedded Context.
   525  type valueCtx struct {
   526  	Context
   527  	key, val interface{}
   528  }
   529  
   530  // stringify tries a bit to stringify v, without using fmt, since we don't
   531  // want context depending on the unicode tables. This is only used by
   532  // *valueCtx.String().
   533  func stringify(v interface{}) string {
   534  	switch s := v.(type) {
   535  	case stringer:
   536  		return s.String()
   537  	case string:
   538  		return s
   539  	}
   540  	return "<not Stringer>"
   541  }
   542  
   543  func (c *valueCtx) String() string {
   544  	return contextName(c.Context) + ".WithValue(type " +
   545  		reflectlite.TypeOf(c.key).String() +
   546  		", val " + stringify(c.val) + ")"
   547  }
   548  
   549  func (c *valueCtx) Value(key interface{}) interface{} {
   550  	if c.key == key {
   551  		return c.val
   552  	}
   553  	return c.Context.Value(key)
   554  }
   555  

View as plain text