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 defer cc.mu.Unlock() 292 return cc.cause 293 } 294 // There is no cancelCtxKey value, so we know that c is 295 // not a descendant of some Context created by WithCancelCause. 296 // Therefore, there is no specific cause to return. 297 // If this is not one of the standard Context types, 298 // it might still have an error even though it won't have a cause. 299 return c.Err() 300 } 301 302 // AfterFunc arranges to call f in its own goroutine after ctx is canceled. 303 // If ctx is already canceled, AfterFunc calls f immediately in its own goroutine. 304 // 305 // Multiple calls to AfterFunc on a context operate independently; 306 // one does not replace another. 307 // 308 // Calling the returned stop function stops the association of ctx with f. 309 // It returns true if the call stopped f from being run. 310 // If stop returns false, 311 // either the context is canceled and f has been started in its own goroutine; 312 // or f was already stopped. 313 // The stop function does not wait for f to complete before returning. 314 // If the caller needs to know whether f is completed, 315 // it must coordinate with f explicitly. 316 // 317 // If ctx has a "AfterFunc(func()) func() bool" method, 318 // AfterFunc will use it to schedule the call. 319 func AfterFunc(ctx Context, f func()) (stop func() bool) { 320 a := &afterFuncCtx{ 321 f: f, 322 } 323 a.cancelCtx.propagateCancel(ctx, a) 324 return func() bool { 325 stopped := false 326 a.once.Do(func() { 327 stopped = true 328 }) 329 if stopped { 330 a.cancel(true, Canceled, nil) 331 } 332 return stopped 333 } 334 } 335 336 type afterFuncer interface { 337 AfterFunc(func()) func() bool 338 } 339 340 type afterFuncCtx struct { 341 cancelCtx 342 once sync.Once // either starts running f or stops f from running 343 f func() 344 } 345 346 func (a *afterFuncCtx) cancel(removeFromParent bool, err, cause error) { 347 a.cancelCtx.cancel(false, err, cause) 348 if removeFromParent { 349 removeChild(a.Context, a) 350 } 351 a.once.Do(func() { 352 go a.f() 353 }) 354 } 355 356 // A stopCtx is used as the parent context of a cancelCtx when 357 // an AfterFunc has been registered with the parent. 358 // It holds the stop function used to unregister the AfterFunc. 359 type stopCtx struct { 360 Context 361 stop func() bool 362 } 363 364 // goroutines counts the number of goroutines ever created; for testing. 365 var goroutines atomic.Int32 366 367 // &cancelCtxKey is the key that a cancelCtx returns itself for. 368 var cancelCtxKey int 369 370 // parentCancelCtx returns the underlying *cancelCtx for parent. 371 // It does this by looking up parent.Value(&cancelCtxKey) to find 372 // the innermost enclosing *cancelCtx and then checking whether 373 // parent.Done() matches that *cancelCtx. (If not, the *cancelCtx 374 // has been wrapped in a custom implementation providing a 375 // different done channel, in which case we should not bypass it.) 376 func parentCancelCtx(parent Context) (*cancelCtx, bool) { 377 done := parent.Done() 378 if done == closedchan || done == nil { 379 return nil, false 380 } 381 p, ok := parent.Value(&cancelCtxKey).(*cancelCtx) 382 if !ok { 383 return nil, false 384 } 385 pdone, _ := p.done.Load().(chan struct{}) 386 if pdone != done { 387 return nil, false 388 } 389 return p, true 390 } 391 392 // removeChild removes a context from its parent. 393 func removeChild(parent Context, child canceler) { 394 if s, ok := parent.(stopCtx); ok { 395 s.stop() 396 return 397 } 398 p, ok := parentCancelCtx(parent) 399 if !ok { 400 return 401 } 402 p.mu.Lock() 403 if p.children != nil { 404 delete(p.children, child) 405 } 406 p.mu.Unlock() 407 } 408 409 // A canceler is a context type that can be canceled directly. The 410 // implementations are *cancelCtx and *timerCtx. 411 type canceler interface { 412 cancel(removeFromParent bool, err, cause error) 413 Done() <-chan struct{} 414 } 415 416 // closedchan is a reusable closed channel. 417 var closedchan = make(chan struct{}) 418 419 func init() { 420 close(closedchan) 421 } 422 423 // A cancelCtx can be canceled. When canceled, it also cancels any children 424 // that implement canceler. 425 type cancelCtx struct { 426 Context 427 428 mu sync.Mutex // protects following fields 429 done atomic.Value // of chan struct{}, created lazily, closed by first cancel call 430 children map[canceler]struct{} // set to nil by the first cancel call 431 err error // set to non-nil by the first cancel call 432 cause error // set to non-nil by the first cancel call 433 } 434 435 func (c *cancelCtx) Value(key any) any { 436 if key == &cancelCtxKey { 437 return c 438 } 439 return value(c.Context, key) 440 } 441 442 func (c *cancelCtx) Done() <-chan struct{} { 443 d := c.done.Load() 444 if d != nil { 445 return d.(chan struct{}) 446 } 447 c.mu.Lock() 448 defer c.mu.Unlock() 449 d = c.done.Load() 450 if d == nil { 451 d = make(chan struct{}) 452 c.done.Store(d) 453 } 454 return d.(chan struct{}) 455 } 456 457 func (c *cancelCtx) Err() error { 458 c.mu.Lock() 459 err := c.err 460 c.mu.Unlock() 461 return err 462 } 463 464 // propagateCancel arranges for child to be canceled when parent is. 465 // It sets the parent context of cancelCtx. 466 func (c *cancelCtx) propagateCancel(parent Context, child canceler) { 467 c.Context = parent 468 469 done := parent.Done() 470 if done == nil { 471 return // parent is never canceled 472 } 473 474 select { 475 case <-done: 476 // parent is already canceled 477 child.cancel(false, parent.Err(), Cause(parent)) 478 return 479 default: 480 } 481 482 if p, ok := parentCancelCtx(parent); ok { 483 // parent is a *cancelCtx, or derives from one. 484 p.mu.Lock() 485 if p.err != nil { 486 // parent has already been canceled 487 child.cancel(false, p.err, p.cause) 488 } else { 489 if p.children == nil { 490 p.children = make(map[canceler]struct{}) 491 } 492 p.children[child] = struct{}{} 493 } 494 p.mu.Unlock() 495 return 496 } 497 498 if a, ok := parent.(afterFuncer); ok { 499 // parent implements an AfterFunc method. 500 c.mu.Lock() 501 stop := a.AfterFunc(func() { 502 child.cancel(false, parent.Err(), Cause(parent)) 503 }) 504 c.Context = stopCtx{ 505 Context: parent, 506 stop: stop, 507 } 508 c.mu.Unlock() 509 return 510 } 511 512 goroutines.Add(1) 513 go func() { 514 select { 515 case <-parent.Done(): 516 child.cancel(false, parent.Err(), Cause(parent)) 517 case <-child.Done(): 518 } 519 }() 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 reflectlite.TypeOf(c).String() 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 != nil { 549 c.mu.Unlock() 550 return // already canceled 551 } 552 c.err = 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 == 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 if !reflectlite.TypeOf(key).Comparable() { 726 panic("key is not comparable") 727 } 728 return &valueCtx{parent, key, val} 729 } 730 731 // A valueCtx carries a key-value pair. It implements Value for that key and 732 // delegates all other calls to the embedded Context. 733 type valueCtx struct { 734 Context 735 key, val any 736 } 737 738 // stringify tries a bit to stringify v, without using fmt, since we don't 739 // want context depending on the unicode tables. This is only used by 740 // *valueCtx.String(). 741 func stringify(v any) string { 742 switch s := v.(type) { 743 case stringer: 744 return s.String() 745 case string: 746 return s 747 case nil: 748 return "<nil>" 749 } 750 return reflectlite.TypeOf(v).String() 751 } 752 753 func (c *valueCtx) String() string { 754 return contextName(c.Context) + ".WithValue(" + 755 stringify(c.key) + ", " + 756 stringify(c.val) + ")" 757 } 758 759 func (c *valueCtx) Value(key any) any { 760 if c.key == key { 761 return c.val 762 } 763 return value(c.Context, key) 764 } 765 766 func value(c Context, key any) any { 767 for { 768 switch ctx := c.(type) { 769 case *valueCtx: 770 if key == ctx.key { 771 return ctx.val 772 } 773 c = ctx.Context 774 case *cancelCtx: 775 if key == &cancelCtxKey { 776 return c 777 } 778 c = ctx.Context 779 case withoutCancelCtx: 780 if key == &cancelCtxKey { 781 // This implements Cause(ctx) == nil 782 // when ctx is created using WithoutCancel. 783 return nil 784 } 785 c = ctx.c 786 case *timerCtx: 787 if key == &cancelCtxKey { 788 return &ctx.cancelCtx 789 } 790 c = ctx.Context 791 case backgroundCtx, todoCtx: 792 return nil 793 default: 794 return c.Value(key) 795 } 796 } 797 } 798