context.mx raw

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