Skip to content

Commit 02302a3

Browse files
authored
Merge branch 'main' into fix-21448
2 parents 9be19ff + 6f48a36 commit 02302a3

File tree

11 files changed

+234
-122
lines changed

11 files changed

+234
-122
lines changed

.golangci.yml

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ linters:
1212
- dupl
1313
#- gocyclo # The cyclomatic complexety of a lot of functions is too high, we should refactor those another time.
1414
- gofmt
15-
- misspell
1615
- gocritic
1716
- bidichk
1817
- ineffassign
@@ -148,9 +147,6 @@ issues:
148147
- path: models/issue_comment_list.go
149148
linters:
150149
- dupl
151-
- linters:
152-
- misspell
153-
text: '`Unknwon` is a misspelling of `Unknown`'
154150
- path: models/update.go
155151
linters:
156152
- unused

Makefile

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ TEST_TAGS ?= sqlite sqlite_unlock_notify
130130
TAR_EXCLUDES := .git data indexers queues log node_modules $(EXECUTABLE) $(FOMANTIC_WORK_DIR)/node_modules $(DIST) $(MAKE_EVIDENCE_DIR) $(AIR_TMP_DIR) $(GO_LICENSE_TMP_DIR)
131131

132132
GO_DIRS := cmd tests models modules routers build services tools
133+
WEB_DIRS := web_src/js web_src/less
133134

134135
GO_SOURCES := $(wildcard *.go)
135136
GO_SOURCES += $(shell find $(GO_DIRS) -type f -name "*.go" -not -path modules/options/bindata.go -not -path modules/public/bindata.go -not -path modules/templates/bindata.go)
@@ -263,11 +264,24 @@ clean:
263264

264265
.PHONY: fmt
265266
fmt:
266-
@MISSPELL_PACKAGE=$(MISSPELL_PACKAGE) GOFUMPT_PACKAGE=$(GOFUMPT_PACKAGE) $(GO) run build/code-batch-process.go gitea-fmt -w '{file-list}'
267+
GOFUMPT_PACKAGE=$(GOFUMPT_PACKAGE) $(GO) run build/code-batch-process.go gitea-fmt -w '{file-list}'
267268
$(eval TEMPLATES := $(shell find templates -type f -name '*.tmpl'))
268269
@# strip whitespace after '{{' and before `}}` unless there is only whitespace before it
269270
@$(SED_INPLACE) -e 's/{{[ ]\{1,\}/{{/g' -e '/^[ ]\{1,\}}}/! s/[ ]\{1,\}}}/}}/g' $(TEMPLATES)
270271

272+
.PHONY: fmt-check
273+
fmt-check: fmt
274+
@diff=$$(git diff $(GO_SOURCES) templates $(WEB_DIRS)); \
275+
if [ -n "$$diff" ]; then \
276+
echo "Please run 'make fmt' and commit the result:"; \
277+
echo "$${diff}"; \
278+
exit 1; \
279+
fi
280+
281+
.PHONY: misspell-check
282+
misspell-check:
283+
go run $(MISSPELL_PACKAGE) -error -i unknwon $(GO_DIRS) $(WEB_DIRS)
284+
271285
.PHONY: vet
272286
vet:
273287
@echo "Running go vet..."
@@ -311,30 +325,14 @@ errcheck:
311325
@echo "Running errcheck..."
312326
$(GO) run $(ERRCHECK_PACKAGE) $(GO_PACKAGES)
313327

314-
.PHONY: fmt-check
315-
fmt-check:
316-
@# get all go files and run gitea-fmt (with gofmt) on them
317-
@diff=$$(MISSPELL_PACKAGE=$(MISSPELL_PACKAGE) GOFUMPT_PACKAGE=$(GOFUMPT_PACKAGE) $(GO) run build/code-batch-process.go gitea-fmt -l '{file-list}'); \
318-
if [ -n "$$diff" ]; then \
319-
echo "Please run 'make fmt' and commit the result:"; \
320-
echo "$${diff}"; \
321-
exit 1; \
322-
fi
323-
@diff2=$$(git diff templates); \
324-
if [ -n "$$diff2" ]; then \
325-
echo "Please run 'make fmt' and commit the result:"; \
326-
echo "$${diff2}"; \
327-
exit 1; \
328-
fi
329-
330328
.PHONY: checks
331329
checks: checks-frontend checks-backend
332330

333331
.PHONY: checks-frontend
334332
checks-frontend: lockfile-check svg-check
335333

336334
.PHONY: checks-backend
337-
checks-backend: tidy-check swagger-check swagger-validate
335+
checks-backend: tidy-check swagger-check fmt-check misspell-check swagger-validate
338336

339337
.PHONY: lint
340338
lint: lint-frontend lint-backend

build/code-batch-process.go

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import (
2020
)
2121

2222
// Windows has a limitation for command line arguments, the size can not exceed 32KB.
23-
// So we have to feed the files to some tools (like gofmt/misspell) batch by batch
23+
// So we have to feed the files to some tools (like gofmt) batch by batch
2424

2525
// We also introduce a `gitea-fmt` command, it does better import formatting than gofmt/goimports. `gitea-fmt` calls `gofmt` internally.
2626

@@ -195,7 +195,6 @@ Options:
195195
196196
Commands:
197197
%[1]s gofmt ...
198-
%[1]s misspell ...
199198
200199
Arguments:
201200
{file-list} the file list
@@ -239,9 +238,9 @@ func containsString(a []string, s string) bool {
239238
return false
240239
}
241240

242-
func giteaFormatGoImports(files []string, hasChangedFiles, doWriteFile bool) error {
241+
func giteaFormatGoImports(files []string, doWriteFile bool) error {
243242
for _, file := range files {
244-
if err := codeformat.FormatGoImports(file, hasChangedFiles, doWriteFile); err != nil {
243+
if err := codeformat.FormatGoImports(file, doWriteFile); err != nil {
245244
log.Printf("failed to format go imports: %s, err=%v", file, err)
246245
return err
247246
}
@@ -280,10 +279,8 @@ func main() {
280279
if containsString(subArgs, "-d") {
281280
log.Print("the -d option is not supported by gitea-fmt")
282281
}
283-
cmdErrors = append(cmdErrors, giteaFormatGoImports(files, containsString(subArgs, "-l"), containsString(subArgs, "-w")))
282+
cmdErrors = append(cmdErrors, giteaFormatGoImports(files, containsString(subArgs, "-w")))
284283
cmdErrors = append(cmdErrors, passThroughCmd("go", append([]string{"run", os.Getenv("GOFUMPT_PACKAGE"), "-extra", "-lang", getGoVersion()}, substArgs...)))
285-
case "misspell":
286-
cmdErrors = append(cmdErrors, passThroughCmd("go", append([]string{"run", os.Getenv("MISSPELL_PACKAGE")}, substArgs...)))
287284
default:
288285
log.Fatalf("unknown cmd: %s %v", subCmd, subArgs)
289286
}

build/codeformat/formatimports.go

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ package codeformat
77
import (
88
"bytes"
99
"errors"
10-
"fmt"
1110
"io"
1211
"os"
1312
"sort"
@@ -159,7 +158,7 @@ func formatGoImports(contentBytes []byte) ([]byte, error) {
159158
}
160159

161160
// FormatGoImports format the imports by our rules (see unit tests)
162-
func FormatGoImports(file string, doChangedFiles, doWriteFile bool) error {
161+
func FormatGoImports(file string, doWriteFile bool) error {
163162
f, err := os.Open(file)
164163
if err != nil {
165164
return err
@@ -183,10 +182,6 @@ func FormatGoImports(file string, doChangedFiles, doWriteFile bool) error {
183182
return nil
184183
}
185184

186-
if doChangedFiles {
187-
fmt.Println(file)
188-
}
189-
190185
if doWriteFile {
191186
f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0o644)
192187
if err != nil {

models/db/index.go

Lines changed: 64 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -8,45 +8,15 @@ import (
88
"context"
99
"errors"
1010
"fmt"
11-
12-
"code.gitea.io/gitea/modules/setting"
1311
)
1412

1513
// ResourceIndex represents a resource index which could be used as issue/release and others
16-
// We can create different tables i.e. issue_index, release_index and etc.
14+
// We can create different tables i.e. issue_index, release_index, etc.
1715
type ResourceIndex struct {
1816
GroupID int64 `xorm:"pk"`
1917
MaxIndex int64 `xorm:"index"`
2018
}
2119

22-
// UpsertResourceIndex the function will not return until it acquires the lock or receives an error.
23-
func UpsertResourceIndex(ctx context.Context, tableName string, groupID int64) (err error) {
24-
// An atomic UPSERT operation (INSERT/UPDATE) is the only operation
25-
// that ensures that the key is actually locked.
26-
switch {
27-
case setting.Database.UseSQLite3 || setting.Database.UsePostgreSQL:
28-
_, err = Exec(ctx, fmt.Sprintf("INSERT INTO %s (group_id, max_index) "+
29-
"VALUES (?,1) ON CONFLICT (group_id) DO UPDATE SET max_index = %s.max_index+1",
30-
tableName, tableName), groupID)
31-
case setting.Database.UseMySQL:
32-
_, err = Exec(ctx, fmt.Sprintf("INSERT INTO %s (group_id, max_index) "+
33-
"VALUES (?,1) ON DUPLICATE KEY UPDATE max_index = max_index+1", tableName),
34-
groupID)
35-
case setting.Database.UseMSSQL:
36-
// https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/
37-
_, err = Exec(ctx, fmt.Sprintf("MERGE %s WITH (HOLDLOCK) as target "+
38-
"USING (SELECT ? AS group_id) AS src "+
39-
"ON src.group_id = target.group_id "+
40-
"WHEN MATCHED THEN UPDATE SET target.max_index = target.max_index+1 "+
41-
"WHEN NOT MATCHED THEN INSERT (group_id, max_index) "+
42-
"VALUES (src.group_id, 1);", tableName),
43-
groupID)
44-
default:
45-
return fmt.Errorf("database type not supported")
46-
}
47-
return err
48-
}
49-
5020
var (
5121
// ErrResouceOutdated represents an error when request resource outdated
5222
ErrResouceOutdated = errors.New("resource outdated")
@@ -59,53 +29,85 @@ const (
5929
MaxDupIndexAttempts = 3
6030
)
6131

62-
// GetNextResourceIndex retried 3 times to generate a resource index
63-
func GetNextResourceIndex(tableName string, groupID int64) (int64, error) {
64-
for i := 0; i < MaxDupIndexAttempts; i++ {
65-
idx, err := getNextResourceIndex(tableName, groupID)
66-
if err == ErrResouceOutdated {
67-
continue
68-
}
32+
// SyncMaxResourceIndex sync the max index with the resource
33+
func SyncMaxResourceIndex(ctx context.Context, tableName string, groupID, maxIndex int64) (err error) {
34+
e := GetEngine(ctx)
35+
36+
// try to update the max_index and acquire the write-lock for the record
37+
res, err := e.Exec(fmt.Sprintf("UPDATE %s SET max_index=? WHERE group_id=? AND max_index<?", tableName), maxIndex, groupID, maxIndex)
38+
if err != nil {
39+
return err
40+
}
41+
affected, err := res.RowsAffected()
42+
if err != nil {
43+
return err
44+
}
45+
if affected == 0 {
46+
// if nothing is updated, the record might not exist or might be larger, it's safe to try to insert it again and then check whether the record exists
47+
_, errIns := e.Exec(fmt.Sprintf("INSERT INTO %s (group_id, max_index) VALUES (?, ?)", tableName), groupID, maxIndex)
48+
var savedIdx int64
49+
has, err := e.SQL(fmt.Sprintf("SELECT max_index FROM %s WHERE group_id=?", tableName), groupID).Get(&savedIdx)
6950
if err != nil {
70-
return 0, err
51+
return err
52+
}
53+
// if the record still doesn't exist, there must be some errors (insert error)
54+
if !has {
55+
if errIns == nil {
56+
return errors.New("impossible error when SyncMaxResourceIndex, insert succeeded but no record is saved")
57+
}
58+
return errIns
7159
}
72-
return idx, nil
7360
}
74-
return 0, ErrGetResourceIndexFailed
61+
return nil
7562
}
7663

77-
// DeleteResouceIndex delete resource index
78-
func DeleteResouceIndex(ctx context.Context, tableName string, groupID int64) error {
79-
_, err := Exec(ctx, fmt.Sprintf("DELETE FROM %s WHERE group_id=?", tableName), groupID)
80-
return err
81-
}
64+
// GetNextResourceIndex generates a resource index, it must run in the same transaction where the resource is created
65+
func GetNextResourceIndex(ctx context.Context, tableName string, groupID int64) (int64, error) {
66+
e := GetEngine(ctx)
8267

83-
// getNextResourceIndex return the next index
84-
func getNextResourceIndex(tableName string, groupID int64) (int64, error) {
85-
ctx, commiter, err := TxContext()
68+
// try to update the max_index to next value, and acquire the write-lock for the record
69+
res, err := e.Exec(fmt.Sprintf("UPDATE %s SET max_index=max_index+1 WHERE group_id=?", tableName), groupID)
8670
if err != nil {
8771
return 0, err
8872
}
89-
defer commiter.Close()
90-
var preIdx int64
91-
if _, err := GetEngine(ctx).SQL(fmt.Sprintf("SELECT max_index FROM %s WHERE group_id = ?", tableName), groupID).Get(&preIdx); err != nil {
73+
affected, err := res.RowsAffected()
74+
if err != nil {
9275
return 0, err
9376
}
94-
95-
if err := UpsertResourceIndex(ctx, tableName, groupID); err != nil {
96-
return 0, err
77+
if affected == 0 {
78+
// this slow path is only for the first time of creating a resource index
79+
_, errIns := e.Exec(fmt.Sprintf("INSERT INTO %s (group_id, max_index) VALUES (?, 0)", tableName), groupID)
80+
res, err = e.Exec(fmt.Sprintf("UPDATE %s SET max_index=max_index+1 WHERE group_id=?", tableName), groupID)
81+
if err != nil {
82+
return 0, err
83+
}
84+
affected, err = res.RowsAffected()
85+
if err != nil {
86+
return 0, err
87+
}
88+
// if the update still can not update any records, the record must not exist and there must be some errors (insert error)
89+
if affected == 0 {
90+
if errIns == nil {
91+
return 0, errors.New("impossible error when GetNextResourceIndex, insert and update both succeeded but no record is updated")
92+
}
93+
return 0, errIns
94+
}
9795
}
9896

99-
var curIdx int64
100-
has, err := GetEngine(ctx).SQL(fmt.Sprintf("SELECT max_index FROM %s WHERE group_id = ? AND max_index=?", tableName), groupID, preIdx+1).Get(&curIdx)
97+
// now, the new index is in database (protected by the transaction and write-lock)
98+
var newIdx int64
99+
has, err := e.SQL(fmt.Sprintf("SELECT max_index FROM %s WHERE group_id=?", tableName), groupID).Get(&newIdx)
101100
if err != nil {
102101
return 0, err
103102
}
104103
if !has {
105-
return 0, ErrResouceOutdated
106-
}
107-
if err := commiter.Commit(); err != nil {
108-
return 0, err
104+
return 0, errors.New("impossible error when GetNextResourceIndex, upsert succeeded but no record can be selected")
109105
}
110-
return curIdx, nil
106+
return newIdx, nil
107+
}
108+
109+
// DeleteResourceIndex delete resource index
110+
func DeleteResourceIndex(ctx context.Context, tableName string, groupID int64) error {
111+
_, err := Exec(ctx, fmt.Sprintf("DELETE FROM %s WHERE group_id=?", tableName), groupID)
112+
return err
111113
}

0 commit comments

Comments
 (0)