-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctx.go
65 lines (52 loc) · 943 Bytes
/
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
package go_otel_auto_instrument
import (
"context"
"sync"
"github.com/pijng/gls"
)
var (
cacheOnce sync.Once
cache ctxCache
)
type ctxCache struct {
mu sync.RWMutex
entries map[int64]context.Context
}
func (c *ctxCache) get(id int64) (context.Context, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
ctx, ok := c.entries[id]
return ctx, ok
}
func (c *ctxCache) set(id int64, ctx context.Context) {
c.mu.Lock()
defer c.mu.Unlock()
c.entries[id] = ctx
}
func init() {
cacheOnce.Do(func() {
cache = ctxCache{
entries: make(map[int64]context.Context),
}
})
}
func setContext(ctx context.Context) {
id := gls.ID()
cache.set(id, ctx)
}
func getContext() context.Context {
id := gls.ID()
ctx, ok := cache.get(id)
if !ok {
ctx = context.Background()
setContext(ctx)
}
return ctx
}
func getParentContext() context.Context {
ctx, ok := cache.get(gls.ParentID())
if !ok {
return nil
}
return ctx
}