Source file src/context/context.go

     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].
    14  //
    15  // A Context may be canceled to indicate that work done on its behalf should stop.
    16  // A Context with a deadline is canceled after the deadline passes.
    17  // When a Context is canceled, all Contexts derived from it are also canceled.
    18  //
    19  // The [WithCancel], [WithDeadline], and [WithTimeout] functions take a
    20  // Context (the parent) and return a derived Context (the child) and a
    21  // [CancelFunc]. Calling the CancelFunc directly cancels the child and its
    22  // children, removes the parent's reference to the child, and stops
    23  // any associated timers. Failing to call the CancelFunc leaks the
    24  // child and its children until the parent is canceled. The go vet tool
    25  // checks that CancelFuncs are used on all control-flow paths.
    26  //
    27  // The [WithCancelCause], [WithDeadlineCause], and [WithTimeoutCause] functions
    28  // return a [CancelCauseFunc], which takes an error and records it as
    29  // the cancellation cause. Calling [Cause] on the canceled context
    30  // or any of its children retrieves the cause. If no cause is specified,
    31  // Cause(ctx) returns the same value as ctx.Err().
    32  //
    33  // Programs that use Contexts should follow these rules to keep interfaces
    34  // consistent across packages and enable static analysis tools to check context
    35  // propagation:
    36  //
    37  // Do not store Contexts inside a struct type; instead, pass a Context
    38  // explicitly to each function that needs it. This is discussed further in
    39  // https://go.dev/blog/context-and-structs. The Context should be the first
    40  // parameter, typically named ctx:
    41  //
    42  //	func DoSomething(ctx context.Context, arg Arg) error {
    43  //		// ... use ctx ...
    44  //	}
    45  //
    46  // Do not pass a nil [Context], even if a function permits it. Pass [context.TODO]
    47  // if you are unsure about which Context to use.
    48  //
    49  // Use context Values only for request-scoped data that transits processes and
    50  // APIs, not for passing optional parameters to functions.
    51  //
    52  // The same Context may be passed to functions running in different goroutines;
    53  // Contexts are safe for simultaneous use by multiple goroutines.
    54  //
    55  // See https://go.dev/blog/context for example code for a server that uses
    56  // Contexts.
    57  package context
    58  
    59  import (
    60  	"errors"
    61  	"internal/reflectlite"
    62  	"sync"
    63  	"sync/atomic"
    64  	"time"
    65  )
    66  
    67  // A Context carries a deadline, a cancellation signal, and other values across
    68  // API boundaries.
    69  //
    70  // Context's methods may be called by multiple goroutines simultaneously.
    71  type Context interface {
    72  	// Deadline returns the time when work done on behalf of this context
    73  	// should be canceled. Deadline returns ok==false when no deadline is
    74  	// set. Successive calls to Deadline return the same results.
    75  	Deadline() (deadline time.Time, ok bool)
    76  
    77  	// Done returns a channel that's closed when work done on behalf of this
    78  	// context should be canceled. Done may return nil if this context can
    79  	// never be canceled. Successive calls to Done return the same value.
    80  	// The close of the Done channel may happen asynchronously,
    81  	// after the cancel function returns.
    82  	//
    83  	// WithCancel arranges for Done to be closed when cancel is called;
    84  	// WithDeadline arranges for Done to be closed when the deadline
    85  	// expires; WithTimeout arranges for Done to be closed when the timeout
    86  	// elapses.
    87  	//
    88  	// Done is provided for use in select statements:
    89  	//
    90  	//  // Stream generates values with DoSomething and sends them to out
    91  	//  // until DoSomething returns an error or ctx.Done is closed.
    92  	//  func Stream(ctx context.Context, out chan<- Value) error {
    93  	//  	for {
    94  	//  		v, err := DoSomething(ctx)
    95  	//  		if err != nil {
    96  	//  			return err
    97  	//  		}
    98  	//  		select {
    99  	//  		case <-ctx.Done():
   100  	//  			return ctx.Err()
   101  	//  		case out <- v:
   102  	//  		}
   103  	//  	}
   104  	//  }
   105  	//
   106  	// See https://blog.golang.org/pipelines for more examples of how to use
   107  	// a Done channel for cancellation.
   108  	Done() <-chan struct{}
   109  
   110  	// If Done is not yet closed, Err returns nil.
   111  	// If Done is closed, Err returns a non-nil error explaining why:
   112  	// DeadlineExceeded if the context's deadline passed,
   113  	// or Canceled if the context was canceled for some other reason.
   114  	// After Err returns a non-nil error, successive calls to Err return the same error.
   115  	Err() error
   116  
   117  	// Value returns the value associated with this context for key, or nil
   118  	// if no value is associated with key. Successive calls to Value with
   119  	// the same key returns the same result.
   120  	//
   121  	// Use context values only for request-scoped data that transits
   122  	// processes and API boundaries, not for passing optional parameters to
   123  	// functions.
   124  	//
   125  	// A key identifies a specific value in a Context. Functions that wish
   126  	// to store values in Context typically allocate a key in a global
   127  	// variable then use that key as the argument to context.WithValue and
   128  	// Context.Value. A key can be any type that supports equality;
   129  	// packages should define keys as an unexported type to avoid
   130  	// collisions.
   131  	//
   132  	// Packages that define a Context key should provide type-safe accessors
   133  	// for the values stored using that key:
   134  	//
   135  	// 	// Package user defines a User type that's stored in Contexts.
   136  	// 	package user
   137  	//
   138  	// 	import "context"
   139  	//
   140  	// 	// User is the type of value stored in the Contexts.
   141  	// 	type User struct {...}
   142  	//
   143  	// 	// key is an unexported type for keys defined in this package.
   144  	// 	// This prevents collisions with keys defined in other packages.
   145  	// 	type key int
   146  	//
   147  	// 	// userKey is the key for user.User values in Contexts. It is
   148  	// 	// unexported; clients use user.NewContext and user.FromContext
   149  	// 	// instead of using this key directly.
   150  	// 	var userKey key
   151  	//
   152  	// 	// NewContext returns a new Context that carries value u.
   153  	// 	func NewContext(ctx context.Context, u *User) context.Context {
   154  	// 		return context.WithValue(ctx, userKey, u)
   155  	// 	}
   156  	//
   157  	// 	// FromContext returns the User value stored in ctx, if any.
   158  	// 	func FromContext(ctx context.Context) (*User, bool) {
   159  	// 		u, ok := ctx.Value(userKey).(*User)
   160  	// 		return u, ok
   161  	// 	}
   162  	Value(key any) any
   163  }
   164  
   165  // Canceled is the error returned by [Context.Err] when the context is canceled
   166  // for some reason other than its deadline passing.
   167  var Canceled = errors.New("context canceled")
   168  
   169  // DeadlineExceeded is the error returned by [Context.Err] when the context is canceled
   170  // due to its deadline passing.
   171  var DeadlineExceeded error = deadlineExceededError{}
   172  
   173  type deadlineExceededError struct{}
   174  
   175  func (deadlineExceededError) Error() string   { return "context deadline exceeded" }
   176  func (deadlineExceededError) Timeout() bool   { return true }
   177  func (deadlineExceededError) Temporary() bool { return true }
   178  
   179  // An emptyCtx is never canceled, has no values, and has no deadline.
   180  // It is the common base of backgroundCtx and todoCtx.
   181  type emptyCtx struct{}
   182  
   183  func (emptyCtx) Deadline() (deadline time.Time, ok bool) {
   184  	return
   185  }
   186  
   187  func (emptyCtx) Done() <-chan struct{} {
   188  	return nil
   189  }
   190  
   191  func (emptyCtx) Err() error {
   192  	return nil
   193  }
   194  
   195  func (emptyCtx) Value(key any) any {
   196  	return nil
   197  }
   198  
   199  type backgroundCtx struct{ emptyCtx }
   200  
   201  func (backgroundCtx) String() string {
   202  	return "context.Background"
   203  }
   204  
   205  type todoCtx struct{ emptyCtx }
   206  
   207  func (todoCtx) String() string {
   208  	return "context.TODO"
   209  }
   210  
   211  // Background returns a non-nil, empty [Context]. It is never canceled, has no
   212  // values, and has no deadline. It is typically used by the main function,
   213  // initialization, and tests, and as the top-level Context for incoming
   214  // requests.
   215  func Background() Context {
   216  	return backgroundCtx{}
   217  }
   218  
   219  // TODO returns a non-nil, empty [Context]. Code should use context.TODO when
   220  // it's unclear which Context to use or it is not yet available (because the
   221  // surrounding function has not yet been extended to accept a Context
   222  // parameter).
   223  func TODO() Context {
   224  	return todoCtx{}
   225  }
   226  
   227  // A CancelFunc tells an operation to abandon its work.
   228  // A CancelFunc does not wait for the work to stop.
   229  // A CancelFunc may be called by multiple goroutines simultaneously.
   230  // After the first call, subsequent calls to a CancelFunc do nothing.
   231  type CancelFunc func()
   232  
   233  // WithCancel returns a derived context that points to the parent context
   234  // but has a new Done channel. The returned context's Done channel is closed
   235  // when the returned cancel function is called or when the parent context's
   236  // Done channel is closed, whichever happens first.
   237  //
   238  // Canceling this context releases resources associated with it, so code should
   239  // call cancel as soon as the operations running in this [Context] complete.
   240  func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
   241  	c := withCancel(parent)
   242  	return c, func() { c.cancel(true, Canceled, nil) }
   243  }
   244  
   245  // A CancelCauseFunc behaves like a [CancelFunc] but additionally sets the cancellation cause.
   246  // This cause can be retrieved by calling [Cause] on the canceled Context or on
   247  // any of its derived Contexts.
   248  //
   249  // If the context has already been canceled, CancelCauseFunc does not set the cause.
   250  // For example, if childContext is derived from parentContext:
   251  //   - if parentContext is canceled with cause1 before childContext is canceled with cause2,
   252  //     then Cause(parentContext) == Cause(childContext) == cause1
   253  //   - if childContext is canceled with cause2 before parentContext is canceled with cause1,
   254  //     then Cause(parentContext) == cause1 and Cause(childContext) == cause2
   255  type CancelCauseFunc func(cause error)
   256  
   257  // WithCancelCause behaves like [WithCancel] but returns a [CancelCauseFunc] instead of a [CancelFunc].
   258  // Calling cancel with a non-nil error (the "cause") records that error in ctx;
   259  // it can then be retrieved using Cause(ctx).
   260  // Calling cancel with nil sets the cause to Canceled.
   261  //
   262  // Example use:
   263  //
   264  //	ctx, cancel := context.WithCancelCause(parent)
   265  //	cancel(myError)
   266  //	ctx.Err() // returns context.Canceled
   267  //	context.Cause(ctx) // returns myError
   268  func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc) {
   269  	c := withCancel(parent)
   270  	return c, func(cause error) { c.cancel(true, Canceled, cause) }
   271  }
   272  
   273  func withCancel(parent Context) *cancelCtx {
   274  	if parent == nil {
   275  		panic("cannot create context from nil parent")
   276  	}
   277  	c := &cancelCtx{}
   278  	c.propagateCancel(parent, c)
   279  	return c
   280  }
   281  
   282  // Cause returns a non-nil error explaining why c was canceled.
   283  // The first cancellation of c or one of its parents sets the cause.
   284  // If that cancellation happened via a call to CancelCauseFunc(err),
   285  // then [Cause] returns err.
   286  // Otherwise Cause(c) returns the same value as c.Err().
   287  // Cause returns nil if c has not been canceled yet.
   288  func Cause(c Context) error {
   289  	if cc, ok := c.Value(&cancelCtxKey).(*cancelCtx); ok {
   290  		cc.mu.Lock()
   291  		cause := cc.cause
   292  		cc.mu.Unlock()
   293  		if cause != nil {
   294  			return cause
   295  		}
   296  		// Either this context is not canceled,
   297  		// or it is canceled and the cancellation happened in a
   298  		// custom context implementation rather than a *cancelCtx.
   299  	}
   300  	// There is no cancelCtxKey value with a cause, so we know that c is
   301  	// not a descendant of some canceled Context created by WithCancelCause.
   302  	// Therefore, there is no specific cause to return.
   303  	// If this is not one of the standard Context types,
   304  	// it might still have an error even though it won't have a cause.
   305  	return c.Err()
   306  }
   307  
   308  // AfterFunc arranges to call f in its own goroutine after ctx is canceled.
   309  // If ctx is already canceled, AfterFunc calls f immediately in its own goroutine.
   310  //
   311  // Multiple calls to AfterFunc on a context operate independently;
   312  // one does not replace another.
   313  //
   314  // Calling the returned stop function stops the association of ctx with f.
   315  // It returns true if the call stopped f from being run.
   316  // If stop returns false,
   317  // either the context is canceled and f has been started in its own goroutine;
   318  // or f was already stopped.
   319  // The stop function does not wait for f to complete before returning.
   320  // If the caller needs to know whether f is completed,
   321  // it must coordinate with f explicitly.
   322  //
   323  // If ctx has a "AfterFunc(func()) func() bool" method,
   324  // AfterFunc will use it to schedule the call.
   325  func AfterFunc(ctx Context, f func()) (stop func() bool) {
   326  	a := &afterFuncCtx{
   327  		f: f,
   328  	}
   329  	a.cancelCtx.propagateCancel(ctx, a)
   330  	return func() bool {
   331  		stopped := false
   332  		a.once.Do(func() {
   333  			stopped = true
   334  		})
   335  		if stopped {
   336  			a.cancel(true, Canceled, nil)
   337  		}
   338  		return stopped
   339  	}
   340  }
   341  
   342  type afterFuncer interface {
   343  	AfterFunc(func()) func() bool
   344  }
   345  
   346  type afterFuncCtx struct {
   347  	cancelCtx
   348  	once sync.Once // either starts running f or stops f from running
   349  	f    func()
   350  }
   351  
   352  func (a *afterFuncCtx) cancel(removeFromParent bool, err, cause error) {
   353  	a.cancelCtx.cancel(false, err, cause)
   354  	if removeFromParent {
   355  		removeChild(a.Context, a)
   356  	}
   357  	a.once.Do(func() {
   358  		go a.f()
   359  	})
   360  }
   361  
   362  // A stopCtx is used as the parent context of a cancelCtx when
   363  // an AfterFunc has been registered with the parent.
   364  // It holds the stop function used to unregister the AfterFunc.
   365  type stopCtx struct {
   366  	Context
   367  	stop func() bool
   368  }
   369  
   370  // goroutines counts the number of goroutines ever created; for testing.
   371  var goroutines atomic.Int32
   372  
   373  // &cancelCtxKey is the key that a cancelCtx returns itself for.
   374  var cancelCtxKey int
   375  
   376  // parentCancelCtx returns the underlying *cancelCtx for parent.
   377  // It does this by looking up parent.Value(&cancelCtxKey) to find
   378  // the innermost enclosing *cancelCtx and then checking whether
   379  // parent.Done() matches that *cancelCtx. (If not, the *cancelCtx
   380  // has been wrapped in a custom implementation providing a
   381  // different done channel, in which case we should not bypass it.)
   382  func parentCancelCtx(parent Context) (*cancelCtx, bool) {
   383  	done := parent.Done()
   384  	if done == closedchan || done == nil {
   385  		return nil, false
   386  	}
   387  	p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)
   388  	if !ok {
   389  		return nil, false
   390  	}
   391  	pdone, _ := p.done.Load().(chan struct{})
   392  	if pdone != done {
   393  		return nil, false
   394  	}
   395  	return p, true
   396  }
   397  
   398  // removeChild removes a context from its parent.
   399  func removeChild(parent Context, child canceler) {
   400  	if s, ok := parent.(stopCtx); ok {
   401  		s.stop()
   402  		return
   403  	}
   404  	p, ok := parentCancelCtx(parent)
   405  	if !ok {
   406  		return
   407  	}
   408  	p.mu.Lock()
   409  	if p.children != nil {
   410  		delete(p.children, child)
   411  	}
   412  	p.mu.Unlock()
   413  }
   414  
   415  // A canceler is a context type that can be canceled directly. The
   416  // implementations are *cancelCtx and *timerCtx.
   417  type canceler interface {
   418  	cancel(removeFromParent bool, err, cause error)
   419  	Done() <-chan struct{}
   420  }
   421  
   422  // closedchan is a reusable closed channel.
   423  var closedchan = make(chan struct{})
   424  
   425  func init() {
   426  	close(closedchan)
   427  }
   428  
   429  // A cancelCtx can be canceled. When canceled, it also cancels any children
   430  // that implement canceler.
   431  type cancelCtx struct {
   432  	Context
   433  
   434  	mu       sync.Mutex            // protects following fields
   435  	done     atomic.Value          // of chan struct{}, created lazily, closed by first cancel call
   436  	children map[canceler]struct{} // set to nil by the first cancel call
   437  	err      atomic.Value          // set to non-nil by the first cancel call
   438  	cause    error                 // set to non-nil by the first cancel call
   439  }
   440  
   441  func (c *cancelCtx) Value(key any) any {
   442  	if key == &cancelCtxKey {
   443  		return c
   444  	}
   445  	return value(c.Context, key)
   446  }
   447  
   448  func (c *cancelCtx) Done() <-chan struct{} {
   449  	d := c.done.Load()
   450  	if d != nil {
   451  		return d.(chan struct{})
   452  	}
   453  	c.mu.Lock()
   454  	defer c.mu.Unlock()
   455  	d = c.done.Load()
   456  	if d == nil {
   457  		d = make(chan struct{})
   458  		c.done.Store(d)
   459  	}
   460  	return d.(chan struct{})
   461  }
   462  
   463  func (c *cancelCtx) Err() error {
   464  	// An atomic load is ~5x faster than a mutex, which can matter in tight loops.
   465  	if err := c.err.Load(); err != nil {
   466  		return err.(error)
   467  	}
   468  	return nil
   469  }
   470  
   471  // propagateCancel arranges for child to be canceled when parent is.
   472  // It sets the parent context of cancelCtx.
   473  func (c *cancelCtx) propagateCancel(parent Context, child canceler) {
   474  	c.Context = parent
   475  
   476  	done := parent.Done()
   477  	if done == nil {
   478  		return // parent is never canceled
   479  	}
   480  
   481  	select {
   482  	case <-done:
   483  		// parent is already canceled
   484  		child.cancel(false, parent.Err(), Cause(parent))
   485  		return
   486  	default:
   487  	}
   488  
   489  	if p, ok := parentCancelCtx(parent); ok {
   490  		// parent is a *cancelCtx, or derives from one.
   491  		p.mu.Lock()
   492  		if err := p.err.Load(); err != nil {
   493  			// parent has already been canceled
   494  			child.cancel(false, err.(error), p.cause)
   495  		} else {
   496  			if p.children == nil {
   497  				p.children = make(map[canceler]struct{})
   498  			}
   499  			p.children[child] = struct{}{}
   500  		}
   501  		p.mu.Unlock()
   502  		return
   503  	}
   504  
   505  	if a, ok := parent.(afterFuncer); ok {
   506  		// parent implements an AfterFunc method.
   507  		c.mu.Lock()
   508  		stop := a.AfterFunc(func() {
   509  			child.cancel(false, parent.Err(), Cause(parent))
   510  		})
   511  		c.Context = stopCtx{
   512  			Context: parent,
   513  			stop:    stop,
   514  		}
   515  		c.mu.Unlock()
   516  		return
   517  	}
   518  
   519  	goroutines.Add(1)
   520  	go func() {
   521  		select {
   522  		case <-parent.Done():
   523  			child.cancel(false, parent.Err(), Cause(parent))
   524  		case <-child.Done():
   525  		}
   526  	}()
   527  }
   528  
   529  type stringer interface {
   530  	String() string
   531  }
   532  
   533  func contextName(c Context) string {
   534  	if s, ok := c.(stringer); ok {
   535  		return s.String()
   536  	}
   537  	return reflectlite.TypeOf(c).String()
   538  }
   539  
   540  func (c *cancelCtx) String() string {
   541  	return contextName(c.Context) + ".WithCancel"
   542  }
   543  
   544  // cancel closes c.done, cancels each of c's children, and, if
   545  // removeFromParent is true, removes c from its parent's children.
   546  // cancel sets c.cause to cause if this is the first time c is canceled.
   547  func (c *cancelCtx) cancel(removeFromParent bool, err, cause error) {
   548  	if err == nil {
   549  		panic("context: internal error: missing cancel error")
   550  	}
   551  	if cause == nil {
   552  		cause = err
   553  	}
   554  	c.mu.Lock()
   555  	if c.err.Load() != nil {
   556  		c.mu.Unlock()
   557  		return // already canceled
   558  	}
   559  	c.err.Store(err)
   560  	c.cause = cause
   561  	d, _ := c.done.Load().(chan struct{})
   562  	if d == nil {
   563  		c.done.Store(closedchan)
   564  	} else {
   565  		close(d)
   566  	}
   567  	for child := range c.children {
   568  		// NOTE: acquiring the child's lock while holding parent's lock.
   569  		child.cancel(false, err, cause)
   570  	}
   571  	c.children = nil
   572  	c.mu.Unlock()
   573  
   574  	if removeFromParent {
   575  		removeChild(c.Context, c)
   576  	}
   577  }
   578  
   579  // WithoutCancel returns a derived context that points to the parent context
   580  // and is not canceled when parent is canceled.
   581  // The returned context returns no Deadline or Err, and its Done channel is nil.
   582  // Calling [Cause] on the returned context returns nil.
   583  func WithoutCancel(parent Context) Context {
   584  	if parent == nil {
   585  		panic("cannot create context from nil parent")
   586  	}
   587  	return withoutCancelCtx{parent}
   588  }
   589  
   590  type withoutCancelCtx struct {
   591  	c Context
   592  }
   593  
   594  func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool) {
   595  	return
   596  }
   597  
   598  func (withoutCancelCtx) Done() <-chan struct{} {
   599  	return nil
   600  }
   601  
   602  func (withoutCancelCtx) Err() error {
   603  	return nil
   604  }
   605  
   606  func (c withoutCancelCtx) Value(key any) any {
   607  	return value(c, key)
   608  }
   609  
   610  func (c withoutCancelCtx) String() string {
   611  	return contextName(c.c) + ".WithoutCancel"
   612  }
   613  
   614  // WithDeadline returns a derived context that points to the parent context
   615  // but has the deadline adjusted to be no later than d. If the parent's
   616  // deadline is already earlier than d, WithDeadline(parent, d) is semantically
   617  // equivalent to parent. The returned [Context.Done] channel is closed when
   618  // the deadline expires, when the returned cancel function is called,
   619  // or when the parent context's Done channel is closed, whichever happens first.
   620  //
   621  // Canceling this context releases resources associated with it, so code should
   622  // call cancel as soon as the operations running in this [Context] complete.
   623  func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
   624  	return WithDeadlineCause(parent, d, nil)
   625  }
   626  
   627  // WithDeadlineCause behaves like [WithDeadline] but also sets the cause of the
   628  // returned Context when the deadline is exceeded. The returned [CancelFunc] does
   629  // not set the cause.
   630  func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc) {
   631  	if parent == nil {
   632  		panic("cannot create context from nil parent")
   633  	}
   634  	if cur, ok := parent.Deadline(); ok && cur.Before(d) {
   635  		// The current deadline is already sooner than the new one.
   636  		return WithCancel(parent)
   637  	}
   638  	c := &timerCtx{
   639  		deadline: d,
   640  	}
   641  	c.cancelCtx.propagateCancel(parent, c)
   642  	dur := time.Until(d)
   643  	if dur <= 0 {
   644  		c.cancel(true, DeadlineExceeded, cause) // deadline has already passed
   645  		return c, func() { c.cancel(false, Canceled, nil) }
   646  	}
   647  	c.mu.Lock()
   648  	defer c.mu.Unlock()
   649  	if c.err.Load() == nil {
   650  		c.timer = time.AfterFunc(dur, func() {
   651  			c.cancel(true, DeadlineExceeded, cause)
   652  		})
   653  	}
   654  	return c, func() { c.cancel(true, Canceled, nil) }
   655  }
   656  
   657  // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
   658  // implement Done and Err. It implements cancel by stopping its timer then
   659  // delegating to cancelCtx.cancel.
   660  type timerCtx struct {
   661  	cancelCtx
   662  	timer *time.Timer // Under cancelCtx.mu.
   663  
   664  	deadline time.Time
   665  }
   666  
   667  func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
   668  	return c.deadline, true
   669  }
   670  
   671  func (c *timerCtx) String() string {
   672  	return contextName(c.cancelCtx.Context) + ".WithDeadline(" +
   673  		c.deadline.String() + " [" +
   674  		time.Until(c.deadline).String() + "])"
   675  }
   676  
   677  func (c *timerCtx) cancel(removeFromParent bool, err, cause error) {
   678  	c.cancelCtx.cancel(false, err, cause)
   679  	if removeFromParent {
   680  		// Remove this timerCtx from its parent cancelCtx's children.
   681  		removeChild(c.cancelCtx.Context, c)
   682  	}
   683  	c.mu.Lock()
   684  	if c.timer != nil {
   685  		c.timer.Stop()
   686  		c.timer = nil
   687  	}
   688  	c.mu.Unlock()
   689  }
   690  
   691  // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
   692  //
   693  // Canceling this context releases resources associated with it, so code should
   694  // call cancel as soon as the operations running in this [Context] complete:
   695  //
   696  //	func slowOperationWithTimeout(ctx context.Context) (Result, error) {
   697  //		ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
   698  //		defer cancel()  // releases resources if slowOperation completes before timeout elapses
   699  //		return slowOperation(ctx)
   700  //	}
   701  func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
   702  	return WithDeadline(parent, time.Now().Add(timeout))
   703  }
   704  
   705  // WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the
   706  // returned Context when the timeout expires. The returned [CancelFunc] does
   707  // not set the cause.
   708  func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc) {
   709  	return WithDeadlineCause(parent, time.Now().Add(timeout), cause)
   710  }
   711  
   712  // WithValue returns a derived context that points to the parent Context.
   713  // In the derived context, the value associated with key is val.
   714  //
   715  // Use context Values only for request-scoped data that transits processes and
   716  // APIs, not for passing optional parameters to functions.
   717  //
   718  // The provided key must be comparable and should not be of type
   719  // string or any other built-in type to avoid collisions between
   720  // packages using context. Users of WithValue should define their own
   721  // types for keys. To avoid allocating when assigning to an
   722  // interface{}, context keys often have concrete type
   723  // struct{}. Alternatively, exported context key variables' static
   724  // type should be a pointer or interface.
   725  func WithValue(parent Context, key, val any) Context {
   726  	if parent == nil {
   727  		panic("cannot create context from nil parent")
   728  	}
   729  	if key == nil {
   730  		panic("nil key")
   731  	}
   732  	if !reflectlite.TypeOf(key).Comparable() {
   733  		panic("key is not comparable")
   734  	}
   735  	return &valueCtx{parent, key, val}
   736  }
   737  
   738  // A valueCtx carries a key-value pair. It implements Value for that key and
   739  // delegates all other calls to the embedded Context.
   740  type valueCtx struct {
   741  	Context
   742  	key, val any
   743  }
   744  
   745  // stringify tries a bit to stringify v, without using fmt, since we don't
   746  // want context depending on the unicode tables. This is only used by
   747  // *valueCtx.String().
   748  func stringify(v any) string {
   749  	switch s := v.(type) {
   750  	case stringer:
   751  		return s.String()
   752  	case string:
   753  		return s
   754  	case nil:
   755  		return "<nil>"
   756  	}
   757  	return reflectlite.TypeOf(v).String()
   758  }
   759  
   760  func (c *valueCtx) String() string {
   761  	return contextName(c.Context) + ".WithValue(" +
   762  		stringify(c.key) + ", " +
   763  		stringify(c.val) + ")"
   764  }
   765  
   766  func (c *valueCtx) Value(key any) any {
   767  	if c.key == key {
   768  		return c.val
   769  	}
   770  	return value(c.Context, key)
   771  }
   772  
   773  func value(c Context, key any) any {
   774  	for {
   775  		switch ctx := c.(type) {
   776  		case *valueCtx:
   777  			if key == ctx.key {
   778  				return ctx.val
   779  			}
   780  			c = ctx.Context
   781  		case *cancelCtx:
   782  			if key == &cancelCtxKey {
   783  				return c
   784  			}
   785  			c = ctx.Context
   786  		case withoutCancelCtx:
   787  			if key == &cancelCtxKey {
   788  				// This implements Cause(ctx) == nil
   789  				// when ctx is created using WithoutCancel.
   790  				return nil
   791  			}
   792  			c = ctx.c
   793  		case *timerCtx:
   794  			if key == &cancelCtxKey {
   795  				return &ctx.cancelCtx
   796  			}
   797  			c = ctx.Context
   798  		case backgroundCtx, todoCtx:
   799  			return nil
   800  		default:
   801  			return c.Value(key)
   802  		}
   803  	}
   804  }
   805  

View as plain text