1
1
mirror of https://github.com/go-gitea/gitea synced 2025-07-22 18:28:37 +00:00

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.
This commit is contained in:
Lunny Xiao
2023-02-15 21:37:34 +08:00
committed by GitHub
parent 03638f9725
commit bd820aa9c5
150 changed files with 663 additions and 516 deletions

View File

@@ -39,7 +39,7 @@ func ToEmail(email *user_model.EmailAddress) *api.Email {
}
// ToBranch convert a git.Commit and git.Branch to an api.Branch
func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git_model.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) {
func ToBranch(ctx context.Context, repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git_model.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) {
if bp == nil {
var hasPerm bool
var canPush bool
@@ -59,7 +59,7 @@ func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git
return &api.Branch{
Name: b.Name,
Commit: ToPayloadCommit(repo, c),
Commit: ToPayloadCommit(ctx, repo, c),
Protected: false,
RequiredApprovals: 0,
EnableStatusCheck: false,
@@ -71,7 +71,7 @@ func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *git
branch := &api.Branch{
Name: b.Name,
Commit: ToPayloadCommit(repo, c),
Commit: ToPayloadCommit(ctx, repo, c),
Protected: true,
RequiredApprovals: bp.RequiredApprovals,
EnableStatusCheck: bp.EnableStatusCheck,
@@ -169,8 +169,8 @@ func ToTag(repo *repo_model.Repository, t *git.Tag) *api.Tag {
}
// ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
func ToVerification(c *git.Commit) *api.PayloadCommitVerification {
verif := asymkey_model.ParseCommitWithSignature(c)
func ToVerification(ctx context.Context, c *git.Commit) *api.PayloadCommitVerification {
verif := asymkey_model.ParseCommitWithSignature(ctx, c)
commitVerification := &api.PayloadCommitVerification{
Verified: verif.Verified,
Reason: verif.Reason,
@@ -271,10 +271,10 @@ func ToDeployKey(apiLink string, key *asymkey_model.DeployKey) *api.DeployKey {
}
// ToOrganization convert user_model.User to api.Organization
func ToOrganization(org *organization.Organization) *api.Organization {
func ToOrganization(ctx context.Context, org *organization.Organization) *api.Organization {
return &api.Organization{
ID: org.ID,
AvatarURL: org.AsUser().AvatarLink(),
AvatarURL: org.AsUser().AvatarLink(ctx),
Name: org.Name,
UserName: org.Name,
FullName: org.FullName,
@@ -287,8 +287,8 @@ func ToOrganization(org *organization.Organization) *api.Organization {
}
// ToTeam convert models.Team to api.Team
func ToTeam(team *organization.Team, loadOrg ...bool) (*api.Team, error) {
teams, err := ToTeams([]*organization.Team{team}, len(loadOrg) != 0 && loadOrg[0])
func ToTeam(ctx context.Context, team *organization.Team, loadOrg ...bool) (*api.Team, error) {
teams, err := ToTeams(ctx, []*organization.Team{team}, len(loadOrg) != 0 && loadOrg[0])
if err != nil || len(teams) == 0 {
return nil, err
}
@@ -296,7 +296,7 @@ func ToTeam(team *organization.Team, loadOrg ...bool) (*api.Team, error) {
}
// ToTeams convert models.Team list to api.Team list
func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
func ToTeams(ctx context.Context, teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
if len(teams) == 0 || teams[0] == nil {
return nil, nil
}
@@ -326,7 +326,7 @@ func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
if err != nil {
return nil, err
}
apiOrg = ToOrganization(org)
apiOrg = ToOrganization(ctx, org)
cache[teams[i].OrgID] = apiOrg
}
apiTeams[i].Organization = apiOrg
@@ -336,7 +336,7 @@ func ToTeams(teams []*organization.Team, loadOrgs bool) ([]*api.Team, error) {
}
// ToAnnotatedTag convert git.Tag to api.AnnotatedTag
func ToAnnotatedTag(repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
func ToAnnotatedTag(ctx context.Context, repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
return &api.AnnotatedTag{
Tag: t.Name,
SHA: t.ID.String(),
@@ -344,7 +344,7 @@ func ToAnnotatedTag(repo *repo_model.Repository, t *git.Tag, c *git.Commit) *api
Message: t.Message,
URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
Tagger: ToCommitUser(t.Tagger),
Verification: ToVerification(c),
Verification: ToVerification(ctx, c),
}
}