| 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 |
// Ensure the done channel has been closed before returning a non-nil error. |
| 467 |
<-c.Done() |
| 468 |
return err.(error) |
| 469 |
} |
| 470 |
return nil |
| 471 |
} |
| 472 |
|
| 473 |
// propagateCancel arranges for child to be canceled when parent is. |
| 474 |
// It sets the parent context of cancelCtx. |
| 475 |
func (c *cancelCtx) propagateCancel(parent Context, child canceler) { |
| 476 |
c.Context = parent |
| 477 |
|
| 478 |
done := parent.Done() |
| 479 |
if done == nil { |
| 480 |
return // parent is never canceled |
| 481 |
} |
| 482 |
|
| 483 |
select { |
| 484 |
case <-done: |
| 485 |
// parent is already canceled |
| 486 |
child.cancel(false, parent.Err(), Cause(parent)) |
| 487 |
return |
| 488 |
default: |
| 489 |
} |
| 490 |
|
| 491 |
if p, ok := parentCancelCtx(parent); ok { |
| 492 |
// parent is a *cancelCtx, or derives from one. |
| 493 |
p.mu.Lock() |
| 494 |
if err := p.err.Load(); err != nil { |
| 495 |
// parent has already been canceled |
| 496 |
child.cancel(false, err.(error), p.cause) |
| 497 |
} else { |
| 498 |
if p.children == nil { |
| 499 |
p.children = make(map[canceler]struct{}) |
| 500 |
} |
| 501 |
p.children[child] = struct{}{} |
| 502 |
} |
| 503 |
p.mu.Unlock() |
| 504 |
return |
| 505 |
} |
| 506 |
|
| 507 |
if a, ok := parent.(afterFuncer); ok { |
| 508 |
// parent implements an AfterFunc method. |
| 509 |
c.mu.Lock() |
| 510 |
stop := a.AfterFunc(func() { |
| 511 |
child.cancel(false, parent.Err(), Cause(parent)) |
| 512 |
}) |
| 513 |
c.Context = stopCtx{ |
| 514 |
Context: parent, |
| 515 |
stop: stop, |
| 516 |
} |
| 517 |
c.mu.Unlock() |
| 518 |
return |
| 519 |
} |
| 520 |
|
| 521 |
goroutines.Add(1) |
| 522 |
go func() { |
| 523 |
select { |
| 524 |
case <-parent.Done(): |
| 525 |
child.cancel(false, parent.Err(), Cause(parent)) |
| 526 |
case <-child.Done(): |
| 527 |
} |
| 528 |
}() |
| 529 |
} |
| 530 |
|
| 531 |
type stringer interface { |
| 532 |
String() string |
| 533 |
} |
| 534 |
|
| 535 |
func contextName(c Context) string { |
| 536 |
if s, ok := c.(stringer); ok { |
| 537 |
return s.String() |
| 538 |
} |
| 539 |
return reflectlite.TypeOf(c).String() |
| 540 |
} |
| 541 |
|
| 542 |
func (c *cancelCtx) String() string { |
| 543 |
return contextName(c.Context) + ".WithCancel" |
| 544 |
} |
| 545 |
|
| 546 |
// cancel closes c.done, cancels each of c's children, and, if |
| 547 |
// removeFromParent is true, removes c from its parent's children. |
| 548 |
// cancel sets c.cause to cause if this is the first time c is canceled. |
| 549 |
func (c *cancelCtx) cancel(removeFromParent bool, err, cause error) { |
| 550 |
if err == nil { |
| 551 |
panic("context: internal error: missing cancel error") |
| 552 |
} |
| 553 |
if cause == nil { |
| 554 |
cause = err |
| 555 |
} |
| 556 |
c.mu.Lock() |
| 557 |
if c.err.Load() != nil { |
| 558 |
c.mu.Unlock() |
| 559 |
return // already canceled |
| 560 |
} |
| 561 |
c.err.Store(err) |
| 562 |
c.cause = cause |
| 563 |
d, _ := c.done.Load().(chan struct{}) |
| 564 |
if d == nil { |
| 565 |
c.done.Store(closedchan) |
| 566 |
} else { |
| 567 |
close(d) |
| 568 |
} |
| 569 |
for child := range c.children { |
| 570 |
// NOTE: acquiring the child's lock while holding parent's lock. |
| 571 |
child.cancel(false, err, cause) |
| 572 |
} |
| 573 |
c.children = nil |
| 574 |
c.mu.Unlock() |
| 575 |
|
| 576 |
if removeFromParent { |
| 577 |
removeChild(c.Context, c) |
| 578 |
} |
| 579 |
} |
| 580 |
|
| 581 |
// WithoutCancel returns a derived context that points to the parent context |
| 582 |
// and is not canceled when parent is canceled. |
| 583 |
// The returned context returns no Deadline or Err, and its Done channel is nil. |
| 584 |
// Calling [Cause] on the returned context returns nil. |
| 585 |
func WithoutCancel(parent Context) Context { |
| 586 |
if parent == nil { |
| 587 |
panic("cannot create context from nil parent") |
| 588 |
} |
| 589 |
return withoutCancelCtx{parent} |
| 590 |
} |
| 591 |
|
| 592 |
type withoutCancelCtx struct { |
| 593 |
c Context |
| 594 |
} |
| 595 |
|
| 596 |
func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool) { |
| 597 |
return |
| 598 |
} |
| 599 |
|
| 600 |
func (withoutCancelCtx) Done() <-chan struct{} { |
| 601 |
return nil |
| 602 |
} |
| 603 |
|
| 604 |
func (withoutCancelCtx) Err() error { |
| 605 |
return nil |
| 606 |
} |
| 607 |
|
| 608 |
func (c withoutCancelCtx) Value(key any) any { |
| 609 |
return value(c, key) |
| 610 |
} |
| 611 |
|
| 612 |
func (c withoutCancelCtx) String() string { |
| 613 |
return contextName(c.c) + ".WithoutCancel" |
| 614 |
} |
| 615 |
|
| 616 |
// WithDeadline returns a derived context that points to the parent context |
| 617 |
// but has the deadline adjusted to be no later than d. If the parent's |
| 618 |
// deadline is already earlier than d, WithDeadline(parent, d) is semantically |
| 619 |
// equivalent to parent. The returned [Context.Done] channel is closed when |
| 620 |
// the deadline expires, when the returned cancel function is called, |
| 621 |
// or when the parent context's Done channel is closed, whichever happens first. |
| 622 |
// |
| 623 |
// Canceling this context releases resources associated with it, so code should |
| 624 |
// call cancel as soon as the operations running in this [Context] complete. |
| 625 |
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { |
| 626 |
return WithDeadlineCause(parent, d, nil) |
| 627 |
} |
| 628 |
|
| 629 |
// WithDeadlineCause behaves like [WithDeadline] but also sets the cause of the |
| 630 |
// returned Context when the deadline is exceeded. The returned [CancelFunc] does |
| 631 |
// not set the cause. |
| 632 |
func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc) { |
| 633 |
if parent == nil { |
| 634 |
panic("cannot create context from nil parent") |
| 635 |
} |
| 636 |
if cur, ok := parent.Deadline(); ok && cur.Before(d) { |
| 637 |
// The current deadline is already sooner than the new one. |
| 638 |
return WithCancel(parent) |
| 639 |
} |
| 640 |
c := &timerCtx{ |
| 641 |
deadline: d, |
| 642 |
} |
| 643 |
c.cancelCtx.propagateCancel(parent, c) |
| 644 |
dur := time.Until(d) |
| 645 |
if dur <= 0 { |
| 646 |
c.cancel(true, DeadlineExceeded, cause) // deadline has already passed |
| 647 |
return c, func() { c.cancel(false, Canceled, nil) } |
| 648 |
} |
| 649 |
c.mu.Lock() |
| 650 |
defer c.mu.Unlock() |
| 651 |
if c.err.Load() == nil { |
| 652 |
c.timer = time.AfterFunc(dur, func() { |
| 653 |
c.cancel(true, DeadlineExceeded, cause) |
| 654 |
}) |
| 655 |
} |
| 656 |
return c, func() { c.cancel(true, Canceled, nil) } |
| 657 |
} |
| 658 |
|
| 659 |
// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to |
| 660 |
// implement Done and Err. It implements cancel by stopping its timer then |
| 661 |
// delegating to cancelCtx.cancel. |
| 662 |
type timerCtx struct { |
| 663 |
cancelCtx |
| 664 |
timer *time.Timer // Under cancelCtx.mu. |
| 665 |
|
| 666 |
deadline time.Time |
| 667 |
} |
| 668 |
|
| 669 |
func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { |
| 670 |
return c.deadline, true |
| 671 |
} |
| 672 |
|
| 673 |
func (c *timerCtx) String() string { |
| 674 |
return contextName(c.cancelCtx.Context) + ".WithDeadline(" + |
| 675 |
c.deadline.String() + " [" + |
| 676 |
time.Until(c.deadline).String() + "])" |
| 677 |
} |
| 678 |
|
| 679 |
func (c *timerCtx) cancel(removeFromParent bool, err, cause error) { |
| 680 |
c.cancelCtx.cancel(false, err, cause) |
| 681 |
if removeFromParent { |
| 682 |
// Remove this timerCtx from its parent cancelCtx's children. |
| 683 |
removeChild(c.cancelCtx.Context, c) |
| 684 |
} |
| 685 |
c.mu.Lock() |
| 686 |
if c.timer != nil { |
| 687 |
c.timer.Stop() |
| 688 |
c.timer = nil |
| 689 |
} |
| 690 |
c.mu.Unlock() |
| 691 |
} |
| 692 |
|
| 693 |
// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). |
| 694 |
// |
| 695 |
// Canceling this context releases resources associated with it, so code should |
| 696 |
// call cancel as soon as the operations running in this [Context] complete: |
| 697 |
// |
| 698 |
// func slowOperationWithTimeout(ctx context.Context) (Result, error) { |
| 699 |
// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) |
| 700 |
// defer cancel() // releases resources if slowOperation completes before timeout elapses |
| 701 |
// return slowOperation(ctx) |
| 702 |
// } |
| 703 |
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { |
| 704 |
return WithDeadline(parent, time.Now().Add(timeout)) |
| 705 |
} |
| 706 |
|
| 707 |
// WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the |
| 708 |
// returned Context when the timeout expires. The returned [CancelFunc] does |
| 709 |
// not set the cause. |
| 710 |
func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc) { |
| 711 |
return WithDeadlineCause(parent, time.Now().Add(timeout), cause) |
| 712 |
} |
| 713 |
|
| 714 |
// WithValue returns a derived context that points to the parent Context. |
| 715 |
// In the derived context, the value associated with key is val. |
| 716 |
// |
| 717 |
// Use context Values only for request-scoped data that transits processes and |
| 718 |
// APIs, not for passing optional parameters to functions. |
| 719 |
// |
| 720 |
// The provided key must be comparable and should not be of type |
| 721 |
// string or any other built-in type to avoid collisions between |
| 722 |
// packages using context. Users of WithValue should define their own |
| 723 |
// types for keys. To avoid allocating when assigning to an |
| 724 |
// interface{}, context keys often have concrete type |
| 725 |
// struct{}. Alternatively, exported context key variables' static |
| 726 |
// type should be a pointer or interface. |
| 727 |
func WithValue(parent Context, key, val any) Context { |
| 728 |
if parent == nil { |
| 729 |
panic("cannot create context from nil parent") |
| 730 |
} |
| 731 |
if key == nil { |
| 732 |
panic("nil key") |
| 733 |
} |
| 734 |
if !reflectlite.TypeOf(key).Comparable() { |
| 735 |
panic("key is not comparable") |
| 736 |
} |
| 737 |
return &valueCtx{parent, key, val} |
| 738 |
} |
| 739 |
|
| 740 |
// A valueCtx carries a key-value pair. It implements Value for that key and |
| 741 |
// delegates all other calls to the embedded Context. |
| 742 |
type valueCtx struct { |
| 743 |
Context |
| 744 |
key, val any |
| 745 |
} |
| 746 |
|
| 747 |
// stringify tries a bit to stringify v, without using fmt, since we don't |
| 748 |
// want context depending on the unicode tables. This is only used by |
| 749 |
// *valueCtx.String(). |
| 750 |
func stringify(v any) string { |
| 751 |
switch s := v.(type) { |
| 752 |
case stringer: |
| 753 |
return s.String() |
| 754 |
case string: |
| 755 |
return s |
| 756 |
case nil: |
| 757 |
return "<nil>" |
| 758 |
} |
| 759 |
return reflectlite.TypeOf(v).String() |
| 760 |
} |
| 761 |
|
| 762 |
func (c *valueCtx) String() string { |
| 763 |
return contextName(c.Context) + ".WithValue(" + |
| 764 |
stringify(c.key) + ", " + |
| 765 |
stringify(c.val) + ")" |
| 766 |
} |
| 767 |
|
| 768 |
func (c *valueCtx) Value(key any) any { |
| 769 |
if c.key == key { |
| 770 |
return c.val |
| 771 |
} |
| 772 |
return value(c.Context, key) |
| 773 |
} |
| 774 |
|
| 775 |
func value(c Context, key any) any { |
| 776 |
for { |
| 777 |
switch ctx := c.(type) { |
| 778 |
case *valueCtx: |
| 779 |
if key == ctx.key { |
| 780 |
return ctx.val |
| 781 |
} |
| 782 |
c = ctx.Context |
| 783 |
case *cancelCtx: |
| 784 |
if key == &cancelCtxKey { |
| 785 |
return c |
| 786 |
} |
| 787 |
c = ctx.Context |
| 788 |
case withoutCancelCtx: |
| 789 |
if key == &cancelCtxKey { |
| 790 |
// This implements Cause(ctx) == nil |
| 791 |
// when ctx is created using WithoutCancel. |
| 792 |
return nil |
| 793 |
} |
| 794 |
c = ctx.c |
| 795 |
case *timerCtx: |
| 796 |
if key == &cancelCtxKey { |
| 797 |
return &ctx.cancelCtx |
| 798 |
} |
| 799 |
c = ctx.Context |
| 800 |
case backgroundCtx, todoCtx: |
| 801 |
return nil |
| 802 |
default: |
| 803 |
return c.Value(key) |
| 804 |
} |
| 805 |
} |
| 806 |
} |