You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user_avatar_test.go 2.4KB

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 year ago
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 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package integration
  4. import (
  5. "bytes"
  6. "fmt"
  7. "image/png"
  8. "io"
  9. "mime/multipart"
  10. "net/http"
  11. "net/url"
  12. "testing"
  13. "code.gitea.io/gitea/models/db"
  14. "code.gitea.io/gitea/models/unittest"
  15. user_model "code.gitea.io/gitea/models/user"
  16. "code.gitea.io/gitea/modules/avatar"
  17. "github.com/stretchr/testify/assert"
  18. )
  19. func TestUserAvatar(t *testing.T) {
  20. onGiteaRun(t, func(t *testing.T, u *url.URL) {
  21. user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo3, is an org
  22. seed := user2.Email
  23. if len(seed) == 0 {
  24. seed = user2.Name
  25. }
  26. img, err := avatar.RandomImage([]byte(seed))
  27. if err != nil {
  28. assert.NoError(t, err)
  29. return
  30. }
  31. session := loginUser(t, "user2")
  32. csrf := GetCSRF(t, session, "/user/settings")
  33. imgData := &bytes.Buffer{}
  34. body := &bytes.Buffer{}
  35. // Setup multi-part
  36. writer := multipart.NewWriter(body)
  37. writer.WriteField("source", "local")
  38. part, err := writer.CreateFormFile("avatar", "avatar-for-testuseravatar.png")
  39. if err != nil {
  40. assert.NoError(t, err)
  41. return
  42. }
  43. if err := png.Encode(imgData, img); err != nil {
  44. assert.NoError(t, err)
  45. return
  46. }
  47. if _, err := io.Copy(part, imgData); err != nil {
  48. assert.NoError(t, err)
  49. return
  50. }
  51. if err := writer.Close(); err != nil {
  52. assert.NoError(t, err)
  53. return
  54. }
  55. req := NewRequestWithBody(t, "POST", "/user/settings/avatar", body)
  56. req.Header.Add("X-Csrf-Token", csrf)
  57. req.Header.Add("Content-Type", writer.FormDataContentType())
  58. session.MakeRequest(t, req, http.StatusSeeOther)
  59. user2 = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo3, is an org
  60. req = NewRequest(t, "GET", user2.AvatarLinkWithSize(db.DefaultContext, 0))
  61. _ = session.MakeRequest(t, req, http.StatusOK)
  62. testGetAvatarRedirect(t, user2)
  63. // Can't test if the response matches because the image is re-generated on upload but checking that this at least doesn't give a 404 should be enough.
  64. })
  65. }
  66. func testGetAvatarRedirect(t *testing.T, user *user_model.User) {
  67. t.Run(fmt.Sprintf("getAvatarRedirect_%s", user.Name), func(t *testing.T) {
  68. req := NewRequestf(t, "GET", "/%s.png", user.Name)
  69. resp := MakeRequest(t, req, http.StatusSeeOther)
  70. assert.EqualValues(t, fmt.Sprintf("/avatars/%s", user.Avatar), resp.Header().Get("location"))
  71. })
  72. }