diff options
author | Lunny Xiao <xiaolunwen@gmail.com> | 2023-02-15 21:37:34 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-02-15 21:37:34 +0800 |
commit | bd820aa9c52da4568b460a0b8604287f8ed8df26 (patch) | |
tree | 15e59e1d4f705b1c5adbd418ed711dfd602a1b25 /modules/repository | |
parent | 03638f9725de3cda5207384098b38462f56d442e (diff) | |
download | gitea-bd820aa9c52da4568b460a0b8604287f8ed8df26.tar.gz gitea-bd820aa9c52da4568b460a0b8604287f8ed8df26.zip |
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.
Diffstat (limited to 'modules/repository')
-rw-r--r-- | modules/repository/commits.go | 12 | ||||
-rw-r--r-- | modules/repository/commits_test.go | 7 | ||||
-rw-r--r-- | modules/repository/repo.go | 6 |
3 files changed, 13 insertions, 12 deletions
diff --git a/modules/repository/commits.go b/modules/repository/commits.go index a47f9b2dc8..96844d5b1d 100644 --- a/modules/repository/commits.go +++ b/modules/repository/commits.go @@ -53,7 +53,7 @@ func (pc *PushCommits) toAPIPayloadCommit(ctx context.Context, repoPath, repoLin authorUsername := "" author, ok := pc.emailUsers[commit.AuthorEmail] if !ok { - author, err = user_model.GetUserByEmail(commit.AuthorEmail) + author, err = user_model.GetUserByEmail(ctx, commit.AuthorEmail) if err == nil { authorUsername = author.Name pc.emailUsers[commit.AuthorEmail] = author @@ -65,7 +65,7 @@ func (pc *PushCommits) toAPIPayloadCommit(ctx context.Context, repoPath, repoLin committerUsername := "" committer, ok := pc.emailUsers[commit.CommitterEmail] if !ok { - committer, err = user_model.GetUserByEmail(commit.CommitterEmail) + committer, err = user_model.GetUserByEmail(ctx, commit.CommitterEmail) if err == nil { // TODO: check errors other than email not found. committerUsername = committer.Name @@ -133,7 +133,7 @@ func (pc *PushCommits) ToAPIPayloadCommits(ctx context.Context, repoPath, repoLi // AvatarLink tries to match user in database with e-mail // in order to show custom avatar, and falls back to general avatar link. -func (pc *PushCommits) AvatarLink(email string) string { +func (pc *PushCommits) AvatarLink(ctx context.Context, email string) string { if pc.avatars == nil { pc.avatars = make(map[string]string) } @@ -147,9 +147,9 @@ func (pc *PushCommits) AvatarLink(email string) string { u, ok := pc.emailUsers[email] if !ok { var err error - u, err = user_model.GetUserByEmail(email) + u, err = user_model.GetUserByEmail(ctx, email) if err != nil { - pc.avatars[email] = avatars.GenerateEmailAvatarFastLink(email, size) + pc.avatars[email] = avatars.GenerateEmailAvatarFastLink(ctx, email, size) if !user_model.IsErrUserNotExist(err) { log.Error("GetUserByEmail: %v", err) return "" @@ -159,7 +159,7 @@ func (pc *PushCommits) AvatarLink(email string) string { } } if u != nil { - pc.avatars[email] = u.AvatarLinkWithSize(size) + pc.avatars[email] = u.AvatarLinkWithSize(ctx, size) } return pc.avatars[email] diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index 2ae4bc73d2..2bd8de38aa 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" system_model "code.gitea.io/gitea/models/system" "code.gitea.io/gitea/models/unittest" @@ -102,7 +103,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) { } func enableGravatar(t *testing.T) { - err := system_model.SetSettingNoVersion(system_model.KeyPictureDisableGravatar, "false") + err := system_model.SetSettingNoVersion(db.DefaultContext, system_model.KeyPictureDisableGravatar, "false") assert.NoError(t, err) setting.GravatarSource = "https://secure.gravatar.com/avatar" err = system_model.Init() @@ -136,13 +137,13 @@ func TestPushCommits_AvatarLink(t *testing.T) { assert.Equal(t, "https://secure.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?d=identicon&s=84", - pushCommits.AvatarLink("user2@example.com")) + pushCommits.AvatarLink(db.DefaultContext, "user2@example.com")) assert.Equal(t, "https://secure.gravatar.com/avatar/"+ fmt.Sprintf("%x", md5.Sum([]byte("nonexistent@example.com")))+ "?d=identicon&s=84", - pushCommits.AvatarLink("nonexistent@example.com")) + pushCommits.AvatarLink(db.DefaultContext, "nonexistent@example.com")) } func TestCommitToPushCommit(t *testing.T) { diff --git a/modules/repository/repo.go b/modules/repository/repo.go index c03e469990..a1dba8fc6a 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -318,7 +318,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository) return nil } - if err := PushUpdateAddTag(repo, gitRepo, tagName, sha1, refname); err != nil { + if err := PushUpdateAddTag(db.DefaultContext, repo, gitRepo, tagName, sha1, refname); err != nil { return fmt.Errorf("unable to PushUpdateAddTag: %q to Repo[%d:%s/%s]: %w", tagName, repo.ID, repo.OwnerName, repo.Name, err) } @@ -328,7 +328,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository) } // PushUpdateAddTag must be called for any push actions to add tag -func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagName, sha1, refname string) error { +func PushUpdateAddTag(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, tagName, sha1, refname string) error { tag, err := gitRepo.GetTagWithID(sha1, tagName) if err != nil { return fmt.Errorf("unable to GetTag: %w", err) @@ -350,7 +350,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagN createdAt := time.Unix(1, 0) if sig != nil { - author, err = user_model.GetUserByEmail(sig.Email) + author, err = user_model.GetUserByEmail(ctx, sig.Email) if err != nil && !user_model.IsErrUserNotExist(err) { return fmt.Errorf("unable to GetUserByEmail for %q: %w", sig.Email, err) } |