Skip to content

Commit fa73cbf

Browse files
realaravinthLoïc Dachary
and
Loïc Dachary
authored
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table. At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists. The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps: 1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes) 2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists 3. Optimize the Gitea uploader to speed up the updates, when possible. The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it. The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration. The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works. The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together. The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo. The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not. The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose. The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues. --- [source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36) Signed-off-by: Loïc Dachary <[email protected]> Co-authored-by: Loïc Dachary <[email protected]>
1 parent a7de80d commit fa73cbf

32 files changed

+451
-332
lines changed

models/fixtures/foreign_reference.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[] # empty

models/foreignreference/error.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2022 Gitea. 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 foreignreference
6+
7+
import (
8+
"fmt"
9+
)
10+
11+
// ErrLocalIndexNotExist represents a "LocalIndexNotExist" kind of error.
12+
type ErrLocalIndexNotExist struct {
13+
RepoID int64
14+
ForeignIndex int64
15+
Type string
16+
}
17+
18+
// ErrLocalIndexNotExist checks if an error is a ErrLocalIndexNotExist.
19+
func IsErrLocalIndexNotExist(err error) bool {
20+
_, ok := err.(ErrLocalIndexNotExist)
21+
return ok
22+
}
23+
24+
func (err ErrLocalIndexNotExist) Error() string {
25+
return fmt.Sprintf("repository %d has no LocalIndex for ForeignIndex %d of type %s", err.RepoID, err.ForeignIndex, err.Type)
26+
}
27+
28+
// ErrForeignIndexNotExist represents a "ForeignIndexNotExist" kind of error.
29+
type ErrForeignIndexNotExist struct {
30+
RepoID int64
31+
LocalIndex int64
32+
Type string
33+
}
34+
35+
// ErrForeignIndexNotExist checks if an error is a ErrForeignIndexNotExist.
36+
func IsErrForeignIndexNotExist(err error) bool {
37+
_, ok := err.(ErrForeignIndexNotExist)
38+
return ok
39+
}
40+
41+
func (err ErrForeignIndexNotExist) Error() string {
42+
return fmt.Sprintf("repository %d has no ForeignIndex for LocalIndex %d of type %s", err.RepoID, err.LocalIndex, err.Type)
43+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2022 Gitea. 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 foreignreference
6+
7+
import (
8+
"code.gitea.io/gitea/models/db"
9+
)
10+
11+
// Type* are valid values for the Type field of ForeignReference
12+
const (
13+
TypeIssue = "issue"
14+
TypePullRequest = "pull_request"
15+
TypeComment = "comment"
16+
TypeReview = "review"
17+
TypeReviewComment = "review_comment"
18+
TypeRelease = "release"
19+
)
20+
21+
// ForeignReference represents external references
22+
type ForeignReference struct {
23+
// RepoID is the first column in all indices. now we only need 2 indices: (repo, local) and (repo, foreign, type)
24+
RepoID int64 `xorm:"UNIQUE(repo_foreign_type) INDEX(repo_local)" `
25+
LocalIndex int64 `xorm:"INDEX(repo_local)"` // the resource key inside Gitea, it can be IssueIndex, or some model ID.
26+
ForeignIndex string `xorm:"INDEX UNIQUE(repo_foreign_type)"`
27+
Type string `xorm:"VARCHAR(16) INDEX UNIQUE(repo_foreign_type)"`
28+
}
29+
30+
func init() {
31+
db.RegisterModel(new(ForeignReference))
32+
}

models/issue.go

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515

1616
admin_model "code.gitea.io/gitea/models/admin"
1717
"code.gitea.io/gitea/models/db"
18+
"code.gitea.io/gitea/models/foreignreference"
1819
"code.gitea.io/gitea/models/issues"
1920
"code.gitea.io/gitea/models/perm"
2021
repo_model "code.gitea.io/gitea/models/repo"
@@ -67,11 +68,12 @@ type Issue struct {
6768
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
6869
ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
6970

70-
Attachments []*repo_model.Attachment `xorm:"-"`
71-
Comments []*Comment `xorm:"-"`
72-
Reactions ReactionList `xorm:"-"`
73-
TotalTrackedTime int64 `xorm:"-"`
74-
Assignees []*user_model.User `xorm:"-"`
71+
Attachments []*repo_model.Attachment `xorm:"-"`
72+
Comments []*Comment `xorm:"-"`
73+
Reactions ReactionList `xorm:"-"`
74+
TotalTrackedTime int64 `xorm:"-"`
75+
Assignees []*user_model.User `xorm:"-"`
76+
ForeignReference *foreignreference.ForeignReference `xorm:"-"`
7577

7678
// IsLocked limits commenting abilities to users on an issue
7779
// with write access
@@ -271,6 +273,29 @@ func (issue *Issue) loadReactions(ctx context.Context) (err error) {
271273
return nil
272274
}
273275

276+
func (issue *Issue) loadForeignReference(ctx context.Context) (err error) {
277+
if issue.ForeignReference != nil {
278+
return nil
279+
}
280+
reference := &foreignreference.ForeignReference{
281+
RepoID: issue.RepoID,
282+
LocalIndex: issue.Index,
283+
Type: foreignreference.TypeIssue,
284+
}
285+
has, err := db.GetEngine(ctx).Get(reference)
286+
if err != nil {
287+
return err
288+
} else if !has {
289+
return foreignreference.ErrForeignIndexNotExist{
290+
RepoID: issue.RepoID,
291+
LocalIndex: issue.Index,
292+
Type: foreignreference.TypeIssue,
293+
}
294+
}
295+
issue.ForeignReference = reference
296+
return nil
297+
}
298+
274299
func (issue *Issue) loadMilestone(e db.Engine) (err error) {
275300
if (issue.Milestone == nil || issue.Milestone.ID != issue.MilestoneID) && issue.MilestoneID > 0 {
276301
issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
@@ -332,6 +357,10 @@ func (issue *Issue) loadAttributes(ctx context.Context) (err error) {
332357
}
333358
}
334359

360+
if err = issue.loadForeignReference(ctx); err != nil && !foreignreference.IsErrForeignIndexNotExist(err) {
361+
return err
362+
}
363+
335364
return issue.loadReactions(ctx)
336365
}
337366

@@ -1110,6 +1139,26 @@ func GetIssueByIndex(repoID, index int64) (*Issue, error) {
11101139
return issue, nil
11111140
}
11121141

1142+
// GetIssueByForeignIndex returns raw issue by foreign ID
1143+
func GetIssueByForeignIndex(ctx context.Context, repoID, foreignIndex int64) (*Issue, error) {
1144+
reference := &foreignreference.ForeignReference{
1145+
RepoID: repoID,
1146+
ForeignIndex: strconv.FormatInt(foreignIndex, 10),
1147+
Type: foreignreference.TypeIssue,
1148+
}
1149+
has, err := db.GetEngine(ctx).Get(reference)
1150+
if err != nil {
1151+
return nil, err
1152+
} else if !has {
1153+
return nil, foreignreference.ErrLocalIndexNotExist{
1154+
RepoID: repoID,
1155+
ForeignIndex: foreignIndex,
1156+
Type: foreignreference.TypeIssue,
1157+
}
1158+
}
1159+
return GetIssueByIndex(repoID, reference.LocalIndex)
1160+
}
1161+
11131162
// GetIssueWithAttrsByIndex returns issue by index in a repository.
11141163
func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
11151164
issue, err := GetIssueByIndex(repoID, index)

models/issue_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@ import (
88
"context"
99
"fmt"
1010
"sort"
11+
"strconv"
1112
"sync"
1213
"testing"
1314
"time"
1415

1516
"code.gitea.io/gitea/models/db"
17+
"code.gitea.io/gitea/models/foreignreference"
1618
repo_model "code.gitea.io/gitea/models/repo"
1719
"code.gitea.io/gitea/models/unittest"
1820
user_model "code.gitea.io/gitea/models/user"
@@ -534,3 +536,35 @@ func TestCorrectIssueStats(t *testing.T) {
534536
assert.NoError(t, err)
535537
assert.EqualValues(t, issueStats.OpenCount, issueAmount)
536538
}
539+
540+
func TestIssueForeignReference(t *testing.T) {
541+
assert.NoError(t, unittest.PrepareTestDatabase())
542+
issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 4}).(*Issue)
543+
assert.NotEqualValues(t, issue.Index, issue.ID) // make sure they are different to avoid false positive
544+
545+
// it is fine for an issue to not have a foreign reference
546+
err := issue.LoadAttributes()
547+
assert.NoError(t, err)
548+
assert.Nil(t, issue.ForeignReference)
549+
550+
var foreignIndex int64 = 12345
551+
_, err = GetIssueByForeignIndex(context.Background(), issue.RepoID, foreignIndex)
552+
assert.True(t, foreignreference.IsErrLocalIndexNotExist(err))
553+
554+
_, err = db.GetEngine(db.DefaultContext).Insert(&foreignreference.ForeignReference{
555+
LocalIndex: issue.Index,
556+
ForeignIndex: strconv.FormatInt(foreignIndex, 10),
557+
RepoID: issue.RepoID,
558+
Type: foreignreference.TypeIssue,
559+
})
560+
assert.NoError(t, err)
561+
562+
err = issue.LoadAttributes()
563+
assert.NoError(t, err)
564+
565+
assert.EqualValues(t, issue.ForeignReference.ForeignIndex, strconv.FormatInt(foreignIndex, 10))
566+
567+
found, err := GetIssueByForeignIndex(context.Background(), issue.RepoID, foreignIndex)
568+
assert.NoError(t, err)
569+
assert.EqualValues(t, found.Index, issue.Index)
570+
}

models/migrate.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,13 @@ func insertIssue(ctx context.Context, issue *Issue) error {
8383
}
8484
}
8585

86+
if issue.ForeignReference != nil {
87+
issue.ForeignReference.LocalIndex = issue.Index
88+
if _, err := sess.Insert(issue.ForeignReference); err != nil {
89+
return err
90+
}
91+
}
92+
8693
return nil
8794
}
8895

models/migrate_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
package models
66

77
import (
8+
"strconv"
89
"testing"
910

11+
"code.gitea.io/gitea/models/foreignreference"
1012
repo_model "code.gitea.io/gitea/models/repo"
1113
"code.gitea.io/gitea/models/unittest"
1214
user_model "code.gitea.io/gitea/models/user"
@@ -45,6 +47,7 @@ func assertCreateIssues(t *testing.T, isPull bool) {
4547
UserID: owner.ID,
4648
}
4749

50+
foreignIndex := int64(12345)
4851
title := "issuetitle1"
4952
is := &Issue{
5053
RepoID: repo.ID,
@@ -58,11 +61,20 @@ func assertCreateIssues(t *testing.T, isPull bool) {
5861
IsClosed: true,
5962
Labels: []*Label{label},
6063
Reactions: []*Reaction{reaction},
64+
ForeignReference: &foreignreference.ForeignReference{
65+
ForeignIndex: strconv.FormatInt(foreignIndex, 10),
66+
RepoID: repo.ID,
67+
Type: foreignreference.TypeIssue,
68+
},
6169
}
6270
err := InsertIssues(is)
6371
assert.NoError(t, err)
6472

6573
i := unittest.AssertExistsAndLoadBean(t, &Issue{Title: title}).(*Issue)
74+
assert.Nil(t, i.ForeignReference)
75+
err = i.LoadAttributes()
76+
assert.NoError(t, err)
77+
assert.EqualValues(t, strconv.FormatInt(foreignIndex, 10), i.ForeignReference.ForeignIndex)
6678
unittest.AssertExistsAndLoadBean(t, &Reaction{Type: "heart", UserID: owner.ID, IssueID: i.ID})
6779
}
6880

models/migrations/migrations.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,8 @@ var migrations = []Migration{
373373
NewMigration("Increase WebAuthentication CredentialID size to 410 - NO-OPED", increaseCredentialIDTo410),
374374
// v210 -> v211
375375
NewMigration("v208 was completely broken - remigrate", remigrateU2FCredentials),
376+
// v211 -> v212
377+
NewMigration("Create ForeignReference table", createForeignReferenceTable),
376378
}
377379

378380
// GetCurrentDBVersion returns the current db version

models/migrations/v211.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Copyright 2022 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 createForeignReferenceTable(x *xorm.Engine) error {
14+
type ForeignReference struct {
15+
// RepoID is the first column in all indices. now we only need 2 indices: (repo, local) and (repo, foreign, type)
16+
RepoID int64 `xorm:"UNIQUE(repo_foreign_type) INDEX(repo_local)" `
17+
LocalIndex int64 `xorm:"INDEX(repo_local)"` // the resource key inside Gitea, it can be IssueIndex, or some model ID.
18+
ForeignIndex string `xorm:"INDEX UNIQUE(repo_foreign_type)"`
19+
Type string `xorm:"VARCHAR(16) INDEX UNIQUE(repo_foreign_type)"`
20+
}
21+
22+
if err := x.Sync2(new(ForeignReference)); err != nil {
23+
return fmt.Errorf("Sync2: %v", err)
24+
}
25+
return nil
26+
}

modules/migration/comment.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@ package migration
77

88
import "time"
99

10+
// Commentable can be commented upon
11+
type Commentable interface {
12+
GetLocalIndex() int64
13+
GetForeignIndex() int64
14+
GetContext() DownloaderContext
15+
}
16+
1017
// Comment is a standard comment information
1118
type Comment struct {
1219
IssueIndex int64 `yaml:"issue_index"`

modules/migration/downloader.go

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,6 @@ import (
1111
"code.gitea.io/gitea/modules/structs"
1212
)
1313

14-
// GetCommentOptions represents an options for get comment
15-
type GetCommentOptions struct {
16-
Context IssueContext
17-
Page int
18-
PageSize int
19-
}
20-
2114
// Downloader downloads the site repo information
2215
type Downloader interface {
2316
SetContext(context.Context)
@@ -27,10 +20,11 @@ type Downloader interface {
2720
GetReleases() ([]*Release, error)
2821
GetLabels() ([]*Label, error)
2922
GetIssues(page, perPage int) ([]*Issue, bool, error)
30-
GetComments(opts GetCommentOptions) ([]*Comment, bool, error)
23+
GetComments(commentable Commentable) ([]*Comment, bool, error)
24+
GetAllComments(page, perPage int) ([]*Comment, bool, error)
3125
SupportGetRepoComments() bool
3226
GetPullRequests(page, perPage int) ([]*PullRequest, bool, error)
33-
GetReviews(pullRequestContext IssueContext) ([]*Review, error)
27+
GetReviews(reviewable Reviewable) ([]*Review, error)
3428
FormatCloneURL(opts MigrateOptions, remoteAddr string) (string, error)
3529
}
3630

@@ -39,3 +33,6 @@ type DownloaderFactory interface {
3933
New(ctx context.Context, opts MigrateOptions) (Downloader, error)
4034
GitServiceType() structs.GitServiceType
4135
}
36+
37+
// DownloaderContext has opaque information only relevant to a given downloader
38+
type DownloaderContext interface{}

0 commit comments

Comments
 (0)