Skip to content

Commit d9c6959

Browse files
authored
Fix commit status index problem (#17061)
* Fix commit status index problem * remove unused functions * Add fixture and test for migration * Fix lint * Fix fixture * Fix lint * Fix test * Fix bug * Fix bug
1 parent d9e237e commit d9c6959

File tree

7 files changed

+211
-19
lines changed

7 files changed

+211
-19
lines changed

models/commit_status.go

Lines changed: 91 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,82 @@ type CommitStatus struct {
4040

4141
func init() {
4242
db.RegisterModel(new(CommitStatus))
43+
db.RegisterModel(new(CommitStatusIndex))
44+
}
45+
46+
// upsertCommitStatusIndex the function will not return until it acquires the lock or receives an error.
47+
func upsertCommitStatusIndex(e db.Engine, repoID int64, sha string) (err error) {
48+
// An atomic UPSERT operation (INSERT/UPDATE) is the only operation
49+
// that ensures that the key is actually locked.
50+
switch {
51+
case setting.Database.UseSQLite3 || setting.Database.UsePostgreSQL:
52+
_, err = e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
53+
"VALUES (?,?,1) ON CONFLICT (repo_id,sha) DO UPDATE SET max_index = `commit_status_index`.max_index+1",
54+
repoID, sha)
55+
case setting.Database.UseMySQL:
56+
_, err = e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+
57+
"VALUES (?,?,1) ON DUPLICATE KEY UPDATE max_index = max_index+1",
58+
repoID, sha)
59+
case setting.Database.UseMSSQL:
60+
// https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/
61+
_, err = e.Exec("MERGE `commit_status_index` WITH (HOLDLOCK) as target "+
62+
"USING (SELECT ? AS repo_id, ? AS sha) AS src "+
63+
"ON src.repo_id = target.repo_id AND src.sha = target.sha "+
64+
"WHEN MATCHED THEN UPDATE SET target.max_index = target.max_index+1 "+
65+
"WHEN NOT MATCHED THEN INSERT (repo_id, sha, max_index) "+
66+
"VALUES (src.repo_id, src.sha, 1);",
67+
repoID, sha)
68+
default:
69+
return fmt.Errorf("database type not supported")
70+
}
71+
return
72+
}
73+
74+
// GetNextCommitStatusIndex retried 3 times to generate a resource index
75+
func GetNextCommitStatusIndex(repoID int64, sha string) (int64, error) {
76+
for i := 0; i < db.MaxDupIndexAttempts; i++ {
77+
idx, err := getNextCommitStatusIndex(repoID, sha)
78+
if err == db.ErrResouceOutdated {
79+
continue
80+
}
81+
if err != nil {
82+
return 0, err
83+
}
84+
return idx, nil
85+
}
86+
return 0, db.ErrGetResourceIndexFailed
87+
}
88+
89+
// getNextCommitStatusIndex return the next index
90+
func getNextCommitStatusIndex(repoID int64, sha string) (int64, error) {
91+
ctx, commiter, err := db.TxContext()
92+
if err != nil {
93+
return 0, err
94+
}
95+
defer commiter.Close()
96+
97+
var preIdx int64
98+
_, err = ctx.Engine().SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ?", repoID, sha).Get(&preIdx)
99+
if err != nil {
100+
return 0, err
101+
}
102+
103+
if err := upsertCommitStatusIndex(ctx.Engine(), repoID, sha); err != nil {
104+
return 0, err
105+
}
106+
107+
var curIdx int64
108+
has, err := ctx.Engine().SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ? AND max_index=?", repoID, sha, preIdx+1).Get(&curIdx)
109+
if err != nil {
110+
return 0, err
111+
}
112+
if !has {
113+
return 0, db.ErrResouceOutdated
114+
}
115+
if err := commiter.Commit(); err != nil {
116+
return 0, err
117+
}
118+
return curIdx, nil
43119
}
44120

45121
func (status *CommitStatus) loadAttributes(e db.Engine) (err error) {
@@ -142,6 +218,14 @@ func sortCommitStatusesSession(sess *xorm.Session, sortType string) {
142218
}
143219
}
144220

221+
// CommitStatusIndex represents a table for commit status index
222+
type CommitStatusIndex struct {
223+
ID int64
224+
RepoID int64 `xorm:"unique(repo_sha)"`
225+
SHA string `xorm:"unique(repo_sha)"`
226+
MaxIndex int64 `xorm:"index"`
227+
}
228+
145229
// GetLatestCommitStatus returns all statuses with a unique context for a given commit.
146230
func GetLatestCommitStatus(repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) {
147231
return getLatestCommitStatus(db.DefaultContext().Engine(), repoID, sha, listOptions)
@@ -206,6 +290,12 @@ func NewCommitStatus(opts NewCommitStatusOptions) error {
206290
return fmt.Errorf("NewCommitStatus[%s, %s]: no user specified", repoPath, opts.SHA)
207291
}
208292

293+
// Get the next Status Index
294+
idx, err := GetNextCommitStatusIndex(opts.Repo.ID, opts.SHA)
295+
if err != nil {
296+
return fmt.Errorf("generate commit status index failed: %v", err)
297+
}
298+
209299
ctx, committer, err := db.TxContext()
210300
if err != nil {
211301
return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", opts.Repo.ID, opts.Creator.ID, opts.SHA, err)
@@ -218,22 +308,7 @@ func NewCommitStatus(opts NewCommitStatusOptions) error {
218308
opts.CommitStatus.SHA = opts.SHA
219309
opts.CommitStatus.CreatorID = opts.Creator.ID
220310
opts.CommitStatus.RepoID = opts.Repo.ID
221-
222-
// Get the next Status Index
223-
var nextIndex int64
224-
lastCommitStatus := &CommitStatus{
225-
SHA: opts.SHA,
226-
RepoID: opts.Repo.ID,
227-
}
228-
has, err := ctx.Engine().Desc("index").Limit(1).Get(lastCommitStatus)
229-
if err != nil {
230-
return fmt.Errorf("NewCommitStatus[%s, %s]: %v", repoPath, opts.SHA, err)
231-
}
232-
if has {
233-
log.Debug("NewCommitStatus[%s, %s]: found", repoPath, opts.SHA)
234-
nextIndex = lastCommitStatus.Index
235-
}
236-
opts.CommitStatus.Index = nextIndex + 1
311+
opts.CommitStatus.Index = idx
237312
log.Debug("NewCommitStatus[%s, %s]: %d", repoPath, opts.SHA, opts.CommitStatus.Index)
238313

239314
opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context)

models/db/index.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,13 @@ var (
5454
)
5555

5656
const (
57-
maxDupIndexAttempts = 3
57+
// MaxDupIndexAttempts max retry times to create index
58+
MaxDupIndexAttempts = 3
5859
)
5960

6061
// GetNextResourceIndex retried 3 times to generate a resource index
6162
func GetNextResourceIndex(tableName string, groupID int64) (int64, error) {
62-
for i := 0; i < maxDupIndexAttempts; i++ {
63+
for i := 0; i < MaxDupIndexAttempts; i++ {
6364
idx, err := getNextResourceIndex(tableName, groupID)
6465
if err == ErrResouceOutdated {
6566
continue
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
-
2+
id: 1
3+
repo_id: 1
4+
sha: "1234123412341234123412341234123412341234"
5+
max_index: 5

models/migrations/migrations.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,8 @@ var migrations = []Migration{
342342
NewMigration("Add repo id column for attachment table", addRepoIDForAttachment),
343343
// v194 -> v195
344344
NewMigration("Add Branch Protection Unprotected Files Column", addBranchProtectionUnprotectedFilesColumn),
345+
// v196 -> v197
346+
NewMigration("Add table commit_status_index", addTableCommitStatusIndex),
345347
}
346348

347349
// GetCurrentDBVersion returns the current db version

models/migrations/v195.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright 2021 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package migrations
6+
7+
import (
8+
"fmt"
9+
10+
"xorm.io/xorm"
11+
)
12+
13+
func addTableCommitStatusIndex(x *xorm.Engine) error {
14+
// CommitStatusIndex represents a table for commit status index
15+
type CommitStatusIndex struct {
16+
ID int64
17+
RepoID int64 `xorm:"unique(repo_sha)"`
18+
SHA string `xorm:"unique(repo_sha)"`
19+
MaxIndex int64 `xorm:"index"`
20+
}
21+
22+
if err := x.Sync2(new(CommitStatusIndex)); err != nil {
23+
return fmt.Errorf("Sync2: %v", err)
24+
}
25+
26+
sess := x.NewSession()
27+
defer sess.Close()
28+
29+
if err := sess.Begin(); err != nil {
30+
return err
31+
}
32+
33+
// Remove data we're goint to rebuild
34+
if _, err := sess.Table("commit_status_index").Where("1=1").Delete(&CommitStatusIndex{}); err != nil {
35+
return err
36+
}
37+
38+
// Create current data for all repositories with issues and PRs
39+
if _, err := sess.Exec("INSERT INTO commit_status_index (repo_id, sha, max_index) " +
40+
"SELECT max_data.repo_id, max_data.sha, max_data.max_index " +
41+
"FROM ( SELECT commit_status.repo_id AS repo_id, commit_status.sha AS sha, max(commit_status.`index`) AS max_index " +
42+
"FROM commit_status GROUP BY commit_status.repo_id, commit_status.sha) AS max_data"); err != nil {
43+
return err
44+
}
45+
46+
return sess.Commit()
47+
}

models/migrations/v195_test.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Copyright 2021 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package migrations
6+
7+
import (
8+
"testing"
9+
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
func Test_addTableCommitStatusIndex(t *testing.T) {
14+
// Create the models used in the migration
15+
type CommitStatus struct {
16+
ID int64 `xorm:"pk autoincr"`
17+
Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
18+
RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
19+
SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
20+
}
21+
22+
// Prepare and load the testing database
23+
x, deferable := prepareTestEnv(t, 0, new(CommitStatus))
24+
if x == nil || t.Failed() {
25+
defer deferable()
26+
return
27+
}
28+
defer deferable()
29+
30+
// Run the migration
31+
if err := addTableCommitStatusIndex(x); err != nil {
32+
assert.NoError(t, err)
33+
return
34+
}
35+
36+
type CommitStatusIndex struct {
37+
ID int64
38+
RepoID int64 `xorm:"unique(repo_sha)"`
39+
SHA string `xorm:"unique(repo_sha)"`
40+
MaxIndex int64 `xorm:"index"`
41+
}
42+
43+
var start = 0
44+
const batchSize = 1000
45+
for {
46+
var indexes = make([]CommitStatusIndex, 0, batchSize)
47+
err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes)
48+
assert.NoError(t, err)
49+
50+
for _, idx := range indexes {
51+
var maxIndex int
52+
has, err := x.SQL("SELECT max(`index`) FROM commit_status WHERE repo_id = ? AND sha = ?", idx.RepoID, idx.SHA).Get(&maxIndex)
53+
assert.NoError(t, err)
54+
assert.True(t, has)
55+
assert.EqualValues(t, maxIndex, idx.MaxIndex)
56+
}
57+
if len(indexes) < batchSize {
58+
break
59+
}
60+
start += len(indexes)
61+
}
62+
}

models/pull.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ func (pr *PullRequest) SetMerged() (bool, error) {
450450
func NewPullRequest(repo *Repository, issue *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
451451
idx, err := db.GetNextResourceIndex("issue_index", repo.ID)
452452
if err != nil {
453-
return fmt.Errorf("generate issue index failed: %v", err)
453+
return fmt.Errorf("generate pull request index failed: %v", err)
454454
}
455455

456456
issue.Index = idx

0 commit comments

Comments
 (0)