Skip to content

Commit 1960ad5

Browse files
authored
Improve cache context (#23330)
Related to: #22294 #23186 #23054 Replace: #23218 Some discussion is in the comments of #23218. Highlights: - Add Expiration for cache context. If a cache context has been used for more than 10s, the cache data will be ignored, and warning logs will be printed. - Add `discard` field to `cacheContext`, a `cacheContext` with `discard` true will drop all cached data and won't store any new one. - Introduce `WithNoCacheContext`, if one wants to run long-life tasks, but the parent context is a cache context, `WithNoCacheContext(perentCtx)` will discard the cache data, so it will be safe to keep the context for a long time. - It will be fine to treat an original context as a cache context, like `GetContextData(context.Backgraud())`, no warning logs will be printed. Some cases about nesting: When: - *A*, *B* or *C* means a cache context. - ~*A*~, ~*B*~ or ~*C*~ means a discard cache context. - `ctx` means `context.Backgrand()` - *A(ctx)* means a cache context with `ctx` as the parent context. - *B(A(ctx))* means a cache context with `A(ctx)` as the parent context. - `With` means `WithCacheContext` - `WithNo` means `WithNoCacheContext` So: - `With(ctx)` -> *A(ctx)* - `With(With(ctx))` -> *A(ctx)*, not *B(A(ctx))* - `With(With(With(ctx)))` -> *A(ctx)*, not *C(B(A(ctx)))* - `WithNo(ctx)` -> *ctx*, not *~A~(ctx)* - `WithNo(With(ctx))` -> *~A~(ctx)* - `WithNo(WithNo(With(ctx)))` -> *~A~(ctx)*, not *~B~(~A~(ctx))* - `With(WithNo(With(ctx)))` -> *B(~A~(ctx))* - `WithNo(With(WithNo(With(ctx))))` -> *~B~(~A~(ctx))* - `With(WithNo(With(WithNo(With(ctx)))))` -> *C(~B~(~A~(ctx)))*
1 parent d949d8e commit 1960ad5

File tree

3 files changed

+141
-18
lines changed

3 files changed

+141
-18
lines changed

Diff for: modules/cache/context.go

+103-16
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package cache
66
import (
77
"context"
88
"sync"
9+
"time"
910

1011
"code.gitea.io/gitea/modules/log"
1112
)
@@ -14,65 +15,151 @@ import (
1415
// This is useful for caching data that is expensive to calculate and is likely to be
1516
// used multiple times in a request.
1617
type cacheContext struct {
17-
ctx context.Context
18-
data map[any]map[any]any
19-
lock sync.RWMutex
18+
data map[any]map[any]any
19+
lock sync.RWMutex
20+
created time.Time
21+
discard bool
2022
}
2123

2224
func (cc *cacheContext) Get(tp, key any) any {
2325
cc.lock.RLock()
2426
defer cc.lock.RUnlock()
25-
if cc.data[tp] == nil {
26-
return nil
27-
}
2827
return cc.data[tp][key]
2928
}
3029

3130
func (cc *cacheContext) Put(tp, key, value any) {
3231
cc.lock.Lock()
3332
defer cc.lock.Unlock()
34-
if cc.data[tp] == nil {
35-
cc.data[tp] = make(map[any]any)
33+
34+
if cc.discard {
35+
return
36+
}
37+
38+
d := cc.data[tp]
39+
if d == nil {
40+
d = make(map[any]any)
41+
cc.data[tp] = d
3642
}
37-
cc.data[tp][key] = value
43+
d[key] = value
3844
}
3945

4046
func (cc *cacheContext) Delete(tp, key any) {
4147
cc.lock.Lock()
4248
defer cc.lock.Unlock()
43-
if cc.data[tp] == nil {
44-
return
45-
}
4649
delete(cc.data[tp], key)
4750
}
4851

52+
func (cc *cacheContext) Discard() {
53+
cc.lock.Lock()
54+
defer cc.lock.Unlock()
55+
cc.data = nil
56+
cc.discard = true
57+
}
58+
59+
func (cc *cacheContext) isDiscard() bool {
60+
cc.lock.RLock()
61+
defer cc.lock.RUnlock()
62+
return cc.discard
63+
}
64+
65+
// cacheContextLifetime is the max lifetime of cacheContext.
66+
// Since cacheContext is used to cache data in a request level context, 10s is enough.
67+
// If a cacheContext is used more than 10s, it's probably misuse.
68+
const cacheContextLifetime = 10 * time.Second
69+
70+
var timeNow = time.Now
71+
72+
func (cc *cacheContext) Expired() bool {
73+
return timeNow().Sub(cc.created) > cacheContextLifetime
74+
}
75+
4976
var cacheContextKey = struct{}{}
5077

78+
/*
79+
Since there are both WithCacheContext and WithNoCacheContext,
80+
it may be confusing when there is nesting.
81+
82+
Some cases to explain the design:
83+
84+
When:
85+
- A, B or C means a cache context.
86+
- A', B' or C' means a discard cache context.
87+
- ctx means context.Backgrand().
88+
- A(ctx) means a cache context with ctx as the parent context.
89+
- B(A(ctx)) means a cache context with A(ctx) as the parent context.
90+
- With is alias of WithCacheContext.
91+
- WithNo is alias of WithNoCacheContext.
92+
93+
So:
94+
- With(ctx) -> A(ctx)
95+
- With(With(ctx)) -> A(ctx), not B(A(ctx)), always reuse parent cache context if possible.
96+
- With(With(With(ctx))) -> A(ctx), not C(B(A(ctx))), ditto.
97+
- WithNo(ctx) -> ctx, not A'(ctx), don't create new cache context if we don't have to.
98+
- WithNo(With(ctx)) -> A'(ctx)
99+
- WithNo(WithNo(With(ctx))) -> A'(ctx), not B'(A'(ctx)), don't create new cache context if we don't have to.
100+
- With(WithNo(With(ctx))) -> B(A'(ctx)), not A(ctx), never reuse a discard cache context.
101+
- WithNo(With(WithNo(With(ctx)))) -> B'(A'(ctx))
102+
- With(WithNo(With(WithNo(With(ctx))))) -> C(B'(A'(ctx))), so there's always only one not-discard cache context.
103+
*/
104+
51105
func WithCacheContext(ctx context.Context) context.Context {
106+
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
107+
if !c.isDiscard() {
108+
// reuse parent context
109+
return ctx
110+
}
111+
}
52112
return context.WithValue(ctx, cacheContextKey, &cacheContext{
53-
ctx: ctx,
54-
data: make(map[any]map[any]any),
113+
data: make(map[any]map[any]any),
114+
created: timeNow(),
55115
})
56116
}
57117

118+
func WithNoCacheContext(ctx context.Context) context.Context {
119+
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
120+
// The caller want to run long-life tasks, but the parent context is a cache context.
121+
// So we should disable and clean the cache data, or it will be kept in memory for a long time.
122+
c.Discard()
123+
return ctx
124+
}
125+
126+
return ctx
127+
}
128+
58129
func GetContextData(ctx context.Context, tp, key any) any {
59130
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
131+
if c.Expired() {
132+
// The warning means that the cache context is misused for long-life task,
133+
// it can be resolved with WithNoCacheContext(ctx).
134+
log.Warn("cache context is expired, may be misused for long-life tasks: %v", c)
135+
return nil
136+
}
60137
return c.Get(tp, key)
61138
}
62-
log.Warn("cannot get cache context when getting data: %v", ctx)
63139
return nil
64140
}
65141

66142
func SetContextData(ctx context.Context, tp, key, value any) {
67143
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
144+
if c.Expired() {
145+
// The warning means that the cache context is misused for long-life task,
146+
// it can be resolved with WithNoCacheContext(ctx).
147+
log.Warn("cache context is expired, may be misused for long-life tasks: %v", c)
148+
return
149+
}
68150
c.Put(tp, key, value)
69151
return
70152
}
71-
log.Warn("cannot get cache context when setting data: %v", ctx)
72153
}
73154

74155
func RemoveContextData(ctx context.Context, tp, key any) {
75156
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
157+
if c.Expired() {
158+
// The warning means that the cache context is misused for long-life task,
159+
// it can be resolved with WithNoCacheContext(ctx).
160+
log.Warn("cache context is expired, may be misused for long-life tasks: %v", c)
161+
return
162+
}
76163
c.Delete(tp, key)
77164
}
78165
}

Diff for: modules/cache/context_test.go

+38-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package cache
66
import (
77
"context"
88
"testing"
9+
"time"
910

1011
"github.com/stretchr/testify/assert"
1112
)
@@ -25,7 +26,7 @@ func TestWithCacheContext(t *testing.T) {
2526
assert.EqualValues(t, 1, v.(int))
2627

2728
RemoveContextData(ctx, field, "my_config1")
28-
RemoveContextData(ctx, field, "my_config2") // remove an non-exist key
29+
RemoveContextData(ctx, field, "my_config2") // remove a non-exist key
2930

3031
v = GetContextData(ctx, field, "my_config1")
3132
assert.Nil(t, v)
@@ -38,4 +39,40 @@ func TestWithCacheContext(t *testing.T) {
3839

3940
v = GetContextData(ctx, field, "my_config1")
4041
assert.EqualValues(t, 1, v)
42+
43+
now := timeNow
44+
defer func() {
45+
timeNow = now
46+
}()
47+
timeNow = func() time.Time {
48+
return now().Add(10 * time.Second)
49+
}
50+
v = GetContextData(ctx, field, "my_config1")
51+
assert.Nil(t, v)
52+
}
53+
54+
func TestWithNoCacheContext(t *testing.T) {
55+
ctx := context.Background()
56+
57+
const field = "system_setting"
58+
59+
v := GetContextData(ctx, field, "my_config1")
60+
assert.Nil(t, v)
61+
SetContextData(ctx, field, "my_config1", 1)
62+
v = GetContextData(ctx, field, "my_config1")
63+
assert.Nil(t, v) // still no cache
64+
65+
ctx = WithCacheContext(ctx)
66+
v = GetContextData(ctx, field, "my_config1")
67+
assert.Nil(t, v)
68+
SetContextData(ctx, field, "my_config1", 1)
69+
v = GetContextData(ctx, field, "my_config1")
70+
assert.NotNil(t, v)
71+
72+
ctx = WithNoCacheContext(ctx)
73+
v = GetContextData(ctx, field, "my_config1")
74+
assert.Nil(t, v)
75+
SetContextData(ctx, field, "my_config1", 1)
76+
v = GetContextData(ctx, field, "my_config1")
77+
assert.Nil(t, v) // still no cache
4178
}

Diff for: services/repository/push.go

-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,6 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error {
8080

8181
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("PushUpdates: %s/%s", optsList[0].RepoUserName, optsList[0].RepoName))
8282
defer finished()
83-
ctx = cache.WithCacheContext(ctx)
8483

8584
repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, optsList[0].RepoUserName, optsList[0].RepoName)
8685
if err != nil {

0 commit comments

Comments
 (0)