/
value_detached_ctx.go
107 lines (94 loc) · 2.48 KB
/
value_detached_ctx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
package http
import (
"context"
"sync"
"time"
)
// valueDetachedCtx removes all values associated with ctx while
// ensuring the transitivity of ctx timeout/cancel.
// After the original ctx timeout/cancel, valueDetachedCtx must release
// the original ctx to ensure that the resources associated with
// original ctx can be GC normally.
type valueDetachedCtx struct {
mu sync.Mutex
ctx context.Context
}
// detachCtxValue creates a new valueDetachedCtx from ctx.
func detachCtxValue(ctx context.Context) context.Context {
if ctx.Done() == nil {
return context.Background()
}
c := valueDetachedCtx{ctx: ctx}
go func() {
<-ctx.Done()
deadline, ok := ctx.Deadline()
c.mu.Lock()
c.ctx = &ctxRemnant{
deadline: deadline,
hasDeadline: ok,
err: ctx.Err(),
done: ctx.Done(),
}
c.mu.Unlock()
}()
return &c
}
// Deadline implements the Deadline method of Context.
func (c *valueDetachedCtx) Deadline() (time.Time, bool) {
c.mu.Lock()
defer c.mu.Unlock()
return c.ctx.Deadline()
}
// Done implements Done method of Context.
func (c *valueDetachedCtx) Done() <-chan struct{} {
c.mu.Lock()
defer c.mu.Unlock()
return c.ctx.Done()
}
// Err implements Err method of Context.
func (c *valueDetachedCtx) Err() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.ctx.Err()
}
// Value always returns nil.
func (c *valueDetachedCtx) Value(_ interface{}) interface{} {
return nil
}
// ctxRemnant is the remnant of valueDetachedCtx after timeout/cancel,
// retains some information of the original ctx, ensure that the original ctx
// can be GC normally.
type ctxRemnant struct {
deadline time.Time
hasDeadline bool
err error
done <-chan struct{}
}
// Deadline returns the saved readline information.
func (c *ctxRemnant) Deadline() (time.Time, bool) {
return c.deadline, c.hasDeadline
}
// Done returns saved Done channel.
func (c *ctxRemnant) Done() <-chan struct{} {
return c.done
}
// Err returns saved error.
func (c *ctxRemnant) Err() error {
return c.err
}
// Value always returns nil.
func (c *ctxRemnant) Value(_ interface{}) interface{} {
return nil
}