The `repository` table has quite a few "count of related objects" fields on it, including the number of issues, closed issues, pull requests, and closed pull requests. These fields specifically will cause deadlocks during concurrent PR merges as documented in #9785. These fields are not used in database queries. In order to eliminate the deadlock possibility on them, I've moved them to be calculated on-demand with caching, with the cache being invalidated in the same places that the recalc used to be triggered. I've supplemented the already in-place automated testing with manual testing performing simple close & reopen of issues & PRs, and the counts which are used in the tabs at the top of the repo page are updated correctly as expected. Near future work: - Similar change can probably be performed to fix #9846 - Last known deadlock identified from #9785; I'm hoping to incorporate the synthetic deadlock test in a near future PR to prevent regressions ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Tests - Tests were already in-place covering these fields; they've been adjusted from using the fields to the new accessor methods. - I added test coverage for Go changes... - [ ] in their respective `*_test.go` for unit tests. - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - I added test coverage for JavaScript changes... - [ ] in `web_src/js/*.test.js` if it can be unit tested. - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)). ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - [x] I did not document these changes and I do not expect someone else to do it. ### Release notes - [ ] I do not want this change to show in the release notes. - [x] I want the title to show in the release notes with a link to this pull request. - [ ] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title. <!--start release-notes-assistant--> ## Release notes <!--URL:https://codeberg.org/forgejo/forgejo--> - Bug fixes - [PR](https://codeberg.org/forgejo/forgejo/pulls/9922): <!--number 9922 --><!--line 0 --><!--description cmVkdWNlIGRlYWRsb2NrcyBtZXJnaW5nIFBScyBieSB1c2luZyBjYWNoaW5nIGZvciByZXBvIGlzc3VlIGNvdW50IHN0YXRz-->reduce deadlocks merging PRs by using caching for repo issue count stats<!--description--> <!--end release-notes-assistant--> Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/9922 Reviewed-by: Gusted <gusted@noreply.codeberg.org> Co-authored-by: Mathieu Fenniak <mathieu@fenniak.net> Co-committed-by: Mathieu Fenniak <mathieu@fenniak.net>
322 lines
10 KiB
Go
322 lines
10 KiB
Go
// Copyright 2014 The Gogs Authors. All rights reserved.
|
|
// Copyright 2017 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package models
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strconv"
|
|
|
|
_ "image/jpeg" // Needed for jpeg support
|
|
|
|
asymkey_model "forgejo.org/models/asymkey"
|
|
"forgejo.org/models/db"
|
|
issues_model "forgejo.org/models/issues"
|
|
access_model "forgejo.org/models/perm/access"
|
|
repo_model "forgejo.org/models/repo"
|
|
"forgejo.org/models/unit"
|
|
user_model "forgejo.org/models/user"
|
|
"forgejo.org/modules/log"
|
|
"forgejo.org/services/stats"
|
|
|
|
"xorm.io/builder"
|
|
)
|
|
|
|
// Init initialize model
|
|
func Init(ctx context.Context) error {
|
|
return unit.LoadUnitConfig()
|
|
}
|
|
|
|
type repoChecker struct {
|
|
querySQL func(ctx context.Context) ([]int64, error)
|
|
correctSQL func(ctx context.Context, id int64) error
|
|
desc string
|
|
}
|
|
|
|
func repoStatsCheck(ctx context.Context, checker *repoChecker) {
|
|
results, err := checker.querySQL(ctx)
|
|
if err != nil {
|
|
log.Error("Select %s: %v", checker.desc, err)
|
|
return
|
|
}
|
|
for _, id := range results {
|
|
select {
|
|
case <-ctx.Done():
|
|
log.Warn("CheckRepoStats: Cancelled before checking %s for with id=%d", checker.desc, id)
|
|
return
|
|
default:
|
|
}
|
|
log.Trace("Updating %s: %d", checker.desc, id)
|
|
err = checker.correctSQL(ctx, id)
|
|
if err != nil {
|
|
log.Error("Update %s[%d]: %v", checker.desc, id, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func StatsCorrectSQL(ctx context.Context, sql any, ids ...any) error {
|
|
args := []any{sql}
|
|
args = append(args, ids...)
|
|
_, err := db.GetEngine(ctx).Exec(args...)
|
|
return err
|
|
}
|
|
|
|
func repoStatsCorrectNumWatches(ctx context.Context, id int64) error {
|
|
return StatsCorrectSQL(ctx, "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=? AND mode<>2) WHERE id=?", id, id)
|
|
}
|
|
|
|
func repoStatsCorrectNumStars(ctx context.Context, id int64) error {
|
|
return StatsCorrectSQL(ctx, "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?", id, id)
|
|
}
|
|
|
|
func labelStatsCorrectNumIssues(ctx context.Context, id int64) error {
|
|
return StatsCorrectSQL(ctx, "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?", id, id)
|
|
}
|
|
|
|
func labelStatsCorrectNumIssuesRepo(ctx context.Context, id int64) error {
|
|
_, err := db.GetEngine(ctx).Exec("UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=id) WHERE repo_id=?", id)
|
|
return err
|
|
}
|
|
|
|
func labelStatsCorrectNumClosedIssues(ctx context.Context, id int64) error {
|
|
return stats.QueueRecalcLabelByID(id)
|
|
}
|
|
|
|
func labelStatsCorrectNumClosedIssuesRepo(ctx context.Context, id int64) error {
|
|
return stats.QueueRecalcLabelByRepoID(id)
|
|
}
|
|
|
|
var milestoneStatsQueryNumIssues = "SELECT `milestone`.id FROM `milestone` WHERE `milestone`.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE `issue`.milestone_id=`milestone`.id AND `issue`.is_closed=?) OR `milestone`.num_issues!=(SELECT COUNT(*) FROM `issue` WHERE `issue`.milestone_id=`milestone`.id)"
|
|
|
|
func milestoneStatsCorrectNumIssuesRepo(ctx context.Context, id int64) error {
|
|
e := db.GetEngine(ctx)
|
|
results, err := e.Query(milestoneStatsQueryNumIssues+" AND `milestone`.repo_id = ?", true, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, result := range results {
|
|
id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
|
|
if err := stats.QueueRecalcMilestoneByID(id); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func userStatsCorrectNumRepos(ctx context.Context, id int64) error {
|
|
return StatsCorrectSQL(ctx, "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?", id, id)
|
|
}
|
|
|
|
func repoStatsCorrectIssueNumComments(ctx context.Context, id int64) error {
|
|
return StatsCorrectSQL(ctx, issues_model.UpdateIssueNumCommentsBuilder(id))
|
|
}
|
|
|
|
func repoStatsCorrectNumIssues(ctx context.Context, id int64) error {
|
|
return repo_model.UpdateRepoIssueNumbers(ctx, id, false, false)
|
|
}
|
|
|
|
func repoStatsCorrectNumPulls(ctx context.Context, id int64) error {
|
|
return repo_model.UpdateRepoIssueNumbers(ctx, id, true, false)
|
|
}
|
|
|
|
func repoStatsCorrectNumClosedIssues(ctx context.Context, id int64) error {
|
|
return repo_model.UpdateRepoIssueNumbers(ctx, id, false, true)
|
|
}
|
|
|
|
func repoStatsCorrectNumClosedPulls(ctx context.Context, id int64) error {
|
|
return repo_model.UpdateRepoIssueNumbers(ctx, id, true, true)
|
|
}
|
|
|
|
// statsQuery returns a function that queries the database for a list of IDs
|
|
// sql could be a string or a *builder.Builder
|
|
func statsQuery(sql any, args ...any) func(context.Context) ([]int64, error) {
|
|
return func(ctx context.Context) ([]int64, error) {
|
|
var ids []int64
|
|
return ids, db.GetEngine(ctx).SQL(sql, args...).Find(&ids)
|
|
}
|
|
}
|
|
|
|
// CheckRepoStats checks the repository stats
|
|
func CheckRepoStats(ctx context.Context) error {
|
|
log.Trace("Doing: CheckRepoStats")
|
|
|
|
checkers := []*repoChecker{
|
|
// Repository.NumWatches
|
|
{
|
|
statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id AND mode<>2)"),
|
|
repoStatsCorrectNumWatches,
|
|
"repository count 'num_watches'",
|
|
},
|
|
// Repository.NumStars
|
|
{
|
|
statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)"),
|
|
repoStatsCorrectNumStars,
|
|
"repository count 'num_stars'",
|
|
},
|
|
// Label.NumIssues
|
|
{
|
|
statsQuery("SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)"),
|
|
labelStatsCorrectNumIssues,
|
|
"label count 'num_issues'",
|
|
},
|
|
// Label.NumClosedIssues
|
|
{
|
|
statsQuery("SELECT `label`.id FROM `label` WHERE `label`.num_closed_issues!=(SELECT COUNT(*) FROM `issue_label`,`issue` WHERE `issue_label`.label_id=`label`.id AND `issue_label`.issue_id=`issue`.id AND `issue`.is_closed=?)", true),
|
|
labelStatsCorrectNumClosedIssues,
|
|
"label count 'num_closed_issues'",
|
|
},
|
|
// Milestone.Num{,Closed}Issues
|
|
{
|
|
statsQuery(milestoneStatsQueryNumIssues, true),
|
|
func(ctx context.Context, milestoneID int64) error {
|
|
return stats.QueueRecalcMilestoneByID(milestoneID)
|
|
},
|
|
"milestone count 'num_closed_issues' and 'num_issues'",
|
|
},
|
|
// User.NumRepos
|
|
{
|
|
statsQuery("SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)"),
|
|
userStatsCorrectNumRepos,
|
|
"user count 'num_repos'",
|
|
},
|
|
// Issue.NumComments
|
|
{
|
|
statsQuery(builder.Select("`issue`.id").From("`issue`").Where(
|
|
builder.Neq{
|
|
"`issue`.num_comments": builder.Select("COUNT(*)").From("`comment`").Where(
|
|
builder.Expr("issue_id = `issue`.id").And(
|
|
builder.In("type", issues_model.ConversationCountedCommentType()),
|
|
),
|
|
),
|
|
},
|
|
),
|
|
),
|
|
repoStatsCorrectIssueNumComments,
|
|
"issue count 'num_comments'",
|
|
},
|
|
}
|
|
for _, checker := range checkers {
|
|
select {
|
|
case <-ctx.Done():
|
|
log.Warn("CheckRepoStats: Cancelled before %s", checker.desc)
|
|
return db.ErrCancelledf("before checking %s", checker.desc)
|
|
default:
|
|
repoStatsCheck(ctx, checker)
|
|
}
|
|
}
|
|
|
|
// FIXME: use checker when stop supporting old fork repo format.
|
|
// ***** START: Repository.NumForks *****
|
|
e := db.GetEngine(ctx)
|
|
results, err := e.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
|
|
if err != nil {
|
|
log.Error("Select repository count 'num_forks': %v", err)
|
|
} else {
|
|
for _, result := range results {
|
|
id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
|
|
select {
|
|
case <-ctx.Done():
|
|
log.Warn("CheckRepoStats: Cancelled")
|
|
return db.ErrCancelledf("during repository count 'num_fork' for repo ID %d", id)
|
|
default:
|
|
}
|
|
log.Trace("Updating repository count 'num_forks': %d", id)
|
|
|
|
repo, err := repo_model.GetRepositoryByID(ctx, id)
|
|
if err != nil {
|
|
log.Error("repo_model.GetRepositoryByID[%d]: %v", id, err)
|
|
continue
|
|
}
|
|
|
|
_, err = e.SQL("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID).Get(&repo.NumForks)
|
|
if err != nil {
|
|
log.Error("Select count of forks[%d]: %v", repo.ID, err)
|
|
continue
|
|
}
|
|
|
|
if _, err = e.ID(repo.ID).Cols("num_forks").Update(repo); err != nil {
|
|
log.Error("UpdateRepository[%d]: %v", id, err)
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
// ***** END: Repository.NumForks *****
|
|
return nil
|
|
}
|
|
|
|
func UpdateRepoStats(ctx context.Context, id int64) error {
|
|
var err error
|
|
|
|
for _, f := range []func(ctx context.Context, id int64) error{
|
|
repoStatsCorrectNumWatches,
|
|
repoStatsCorrectNumStars,
|
|
repoStatsCorrectNumIssues,
|
|
repoStatsCorrectNumPulls,
|
|
repoStatsCorrectNumClosedIssues,
|
|
repoStatsCorrectNumClosedPulls,
|
|
labelStatsCorrectNumIssuesRepo,
|
|
labelStatsCorrectNumClosedIssuesRepo,
|
|
milestoneStatsCorrectNumIssuesRepo,
|
|
} {
|
|
err = f(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DoctorUserStarNum recalculate Stars number for all user
|
|
func DoctorUserStarNum(ctx context.Context) (err error) {
|
|
_, err = db.Exec(ctx, "UPDATE `user` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE uid=`user`.id) WHERE type = 0")
|
|
log.Debug("recalculate Stars number for all user finished")
|
|
return err
|
|
}
|
|
|
|
// DeleteDeployKey delete deploy keys
|
|
func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error {
|
|
key, err := asymkey_model.GetDeployKeyByID(ctx, id)
|
|
if err != nil {
|
|
if asymkey_model.IsErrDeployKeyNotExist(err) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("GetDeployKeyByID: %w", err)
|
|
}
|
|
|
|
// Check if user has access to delete this key.
|
|
if !doer.IsAdmin {
|
|
repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID)
|
|
if err != nil {
|
|
return fmt.Errorf("GetRepositoryByID: %w", err)
|
|
}
|
|
has, err := access_model.IsUserRepoAdmin(ctx, repo, doer)
|
|
if err != nil {
|
|
return fmt.Errorf("GetUserRepoPermission: %w", err)
|
|
} else if !has {
|
|
return asymkey_model.ErrKeyAccessDenied{
|
|
UserID: doer.ID,
|
|
KeyID: key.ID,
|
|
Note: "deploy",
|
|
}
|
|
}
|
|
}
|
|
|
|
if _, err := db.DeleteByID[asymkey_model.DeployKey](ctx, key.ID); err != nil {
|
|
return fmt.Errorf("delete deploy key [%d]: %w", key.ID, err)
|
|
}
|
|
|
|
// Check if this is the last reference to same key content.
|
|
has, err := asymkey_model.IsDeployKeyExistByKeyID(ctx, key.KeyID)
|
|
if err != nil {
|
|
return err
|
|
} else if !has {
|
|
if _, err = db.DeleteByID[asymkey_model.PublicKey](ctx, key.KeyID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|