您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

context_test.go 1.9KB

Add context cache as a request level cache (#22294) To avoid duplicated load of the same data in an HTTP request, we can set a context cache to do that. i.e. Some pages may load a user from a database with the same id in different areas on the same page. But the code is hidden in two different deep logic. How should we share the user? As a result of this PR, now if both entry functions accept `context.Context` as the first parameter and we just need to refactor `GetUserByID` to reuse the user from the context cache. Then it will not be loaded twice on an HTTP request. But of course, sometimes we would like to reload an object from the database, that's why `RemoveContextData` is also exposed. The core context cache is here. It defines a new context ```go type cacheContext struct { ctx context.Context data map[any]map[any]any lock sync.RWMutex } var cacheContextKey = struct{}{} func WithCacheContext(ctx context.Context) context.Context { return context.WithValue(ctx, cacheContextKey, &cacheContext{ ctx: ctx, data: make(map[any]map[any]any), }) } ``` Then you can use the below 4 methods to read/write/del the data within the same context. ```go func GetContextData(ctx context.Context, tp, key any) any func SetContextData(ctx context.Context, tp, key, value any) func RemoveContextData(ctx context.Context, tp, key any) func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error) ``` Then let's take a look at how `system.GetString` implement it. ```go func GetSetting(ctx context.Context, key string) (string, error) { return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) { return cache.GetString(genSettingCacheKey(key), func() (string, error) { res, err := GetSettingNoCache(ctx, key) if err != nil { return "", err } return res.SettingValue, nil }) }) } ``` First, it will check if context data include the setting object with the key. If not, it will query from the global cache which may be memory or a Redis cache. If not, it will get the object from the database. In the end, if the object gets from the global cache or database, it will be set into the context cache. An object stored in the context cache will only be destroyed after the context disappeared.
1年前
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年前
Add context cache as a request level cache (#22294) To avoid duplicated load of the same data in an HTTP request, we can set a context cache to do that. i.e. Some pages may load a user from a database with the same id in different areas on the same page. But the code is hidden in two different deep logic. How should we share the user? As a result of this PR, now if both entry functions accept `context.Context` as the first parameter and we just need to refactor `GetUserByID` to reuse the user from the context cache. Then it will not be loaded twice on an HTTP request. But of course, sometimes we would like to reload an object from the database, that's why `RemoveContextData` is also exposed. The core context cache is here. It defines a new context ```go type cacheContext struct { ctx context.Context data map[any]map[any]any lock sync.RWMutex } var cacheContextKey = struct{}{} func WithCacheContext(ctx context.Context) context.Context { return context.WithValue(ctx, cacheContextKey, &cacheContext{ ctx: ctx, data: make(map[any]map[any]any), }) } ``` Then you can use the below 4 methods to read/write/del the data within the same context. ```go func GetContextData(ctx context.Context, tp, key any) any func SetContextData(ctx context.Context, tp, key, value any) func RemoveContextData(ctx context.Context, tp, key any) func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error) ``` Then let's take a look at how `system.GetString` implement it. ```go func GetSetting(ctx context.Context, key string) (string, error) { return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) { return cache.GetString(genSettingCacheKey(key), func() (string, error) { res, err := GetSettingNoCache(ctx, key) if err != nil { return "", err } return res.SettingValue, nil }) }) } ``` First, it will check if context data include the setting object with the key. If not, it will query from the global cache which may be memory or a Redis cache. If not, it will get the object from the database. In the end, if the object gets from the global cache or database, it will be set into the context cache. An object stored in the context cache will only be destroyed after the context disappeared.
1年前
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年前
Add context cache as a request level cache (#22294) To avoid duplicated load of the same data in an HTTP request, we can set a context cache to do that. i.e. Some pages may load a user from a database with the same id in different areas on the same page. But the code is hidden in two different deep logic. How should we share the user? As a result of this PR, now if both entry functions accept `context.Context` as the first parameter and we just need to refactor `GetUserByID` to reuse the user from the context cache. Then it will not be loaded twice on an HTTP request. But of course, sometimes we would like to reload an object from the database, that's why `RemoveContextData` is also exposed. The core context cache is here. It defines a new context ```go type cacheContext struct { ctx context.Context data map[any]map[any]any lock sync.RWMutex } var cacheContextKey = struct{}{} func WithCacheContext(ctx context.Context) context.Context { return context.WithValue(ctx, cacheContextKey, &cacheContext{ ctx: ctx, data: make(map[any]map[any]any), }) } ``` Then you can use the below 4 methods to read/write/del the data within the same context. ```go func GetContextData(ctx context.Context, tp, key any) any func SetContextData(ctx context.Context, tp, key, value any) func RemoveContextData(ctx context.Context, tp, key any) func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error) ``` Then let's take a look at how `system.GetString` implement it. ```go func GetSetting(ctx context.Context, key string) (string, error) { return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) { return cache.GetString(genSettingCacheKey(key), func() (string, error) { res, err := GetSettingNoCache(ctx, key) if err != nil { return "", err } return res.SettingValue, nil }) }) } ``` First, it will check if context data include the setting object with the key. If not, it will query from the global cache which may be memory or a Redis cache. If not, it will get the object from the database. In the end, if the object gets from the global cache or database, it will be set into the context cache. An object stored in the context cache will only be destroyed after the context disappeared.
1年前
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年前
Add context cache as a request level cache (#22294) To avoid duplicated load of the same data in an HTTP request, we can set a context cache to do that. i.e. Some pages may load a user from a database with the same id in different areas on the same page. But the code is hidden in two different deep logic. How should we share the user? As a result of this PR, now if both entry functions accept `context.Context` as the first parameter and we just need to refactor `GetUserByID` to reuse the user from the context cache. Then it will not be loaded twice on an HTTP request. But of course, sometimes we would like to reload an object from the database, that's why `RemoveContextData` is also exposed. The core context cache is here. It defines a new context ```go type cacheContext struct { ctx context.Context data map[any]map[any]any lock sync.RWMutex } var cacheContextKey = struct{}{} func WithCacheContext(ctx context.Context) context.Context { return context.WithValue(ctx, cacheContextKey, &cacheContext{ ctx: ctx, data: make(map[any]map[any]any), }) } ``` Then you can use the below 4 methods to read/write/del the data within the same context. ```go func GetContextData(ctx context.Context, tp, key any) any func SetContextData(ctx context.Context, tp, key, value any) func RemoveContextData(ctx context.Context, tp, key any) func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error) ``` Then let's take a look at how `system.GetString` implement it. ```go func GetSetting(ctx context.Context, key string) (string, error) { return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) { return cache.GetString(genSettingCacheKey(key), func() (string, error) { res, err := GetSettingNoCache(ctx, key) if err != nil { return "", err } return res.SettingValue, nil }) }) } ``` First, it will check if context data include the setting object with the key. If not, it will query from the global cache which may be memory or a Redis cache. If not, it will get the object from the database. In the end, if the object gets from the global cache or database, it will be set into the context cache. An object stored in the context cache will only be destroyed after the context disappeared.
1年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cache
  4. import (
  5. "context"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. func TestWithCacheContext(t *testing.T) {
  11. ctx := WithCacheContext(context.Background())
  12. v := GetContextData(ctx, "empty_field", "my_config1")
  13. assert.Nil(t, v)
  14. const field = "system_setting"
  15. v = GetContextData(ctx, field, "my_config1")
  16. assert.Nil(t, v)
  17. SetContextData(ctx, field, "my_config1", 1)
  18. v = GetContextData(ctx, field, "my_config1")
  19. assert.NotNil(t, v)
  20. assert.EqualValues(t, 1, v.(int))
  21. RemoveContextData(ctx, field, "my_config1")
  22. RemoveContextData(ctx, field, "my_config2") // remove a non-exist key
  23. v = GetContextData(ctx, field, "my_config1")
  24. assert.Nil(t, v)
  25. vInt, err := GetWithContextCache(ctx, field, "my_config1", func() (int, error) {
  26. return 1, nil
  27. })
  28. assert.NoError(t, err)
  29. assert.EqualValues(t, 1, vInt)
  30. v = GetContextData(ctx, field, "my_config1")
  31. assert.EqualValues(t, 1, v)
  32. now := timeNow
  33. defer func() {
  34. timeNow = now
  35. }()
  36. timeNow = func() time.Time {
  37. return now().Add(10 * time.Second)
  38. }
  39. v = GetContextData(ctx, field, "my_config1")
  40. assert.Nil(t, v)
  41. }
  42. func TestWithNoCacheContext(t *testing.T) {
  43. ctx := context.Background()
  44. const field = "system_setting"
  45. v := GetContextData(ctx, field, "my_config1")
  46. assert.Nil(t, v)
  47. SetContextData(ctx, field, "my_config1", 1)
  48. v = GetContextData(ctx, field, "my_config1")
  49. assert.Nil(t, v) // still no cache
  50. ctx = WithCacheContext(ctx)
  51. v = GetContextData(ctx, field, "my_config1")
  52. assert.Nil(t, v)
  53. SetContextData(ctx, field, "my_config1", 1)
  54. v = GetContextData(ctx, field, "my_config1")
  55. assert.NotNil(t, v)
  56. ctx = WithNoCacheContext(ctx)
  57. v = GetContextData(ctx, field, "my_config1")
  58. assert.Nil(t, v)
  59. SetContextData(ctx, field, "my_config1", 1)
  60. v = GetContextData(ctx, field, "my_config1")
  61. assert.Nil(t, v) // still no cache
  62. }