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