aboutsummaryrefslogtreecommitdiffstats
path: root/models
diff options
context:
space:
mode:
authorAravinth Manivannan <realaravinth@batsense.net>2022-03-17 22:38:35 +0530
committerGitHub <noreply@github.com>2022-03-17 18:08:35 +0100
commitfa73cbf5a7e84fab50ad5c8f3095b4dec8b4e879 (patch)
tree69f928ac87307c36577343853e884bb721718add /models
parenta7de80db0d69e98b3d5cf9ba0c6d7608365289bc (diff)
downloadgitea-fa73cbf5a7e84fab50ad5c8f3095b4dec8b4e879.tar.gz
gitea-fa73cbf5a7e84fab50ad5c8f3095b4dec8b4e879.zip
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 <loic@dachary.org> Co-authored-by: Loïc Dachary <loic@dachary.org>
Diffstat (limited to 'models')
-rw-r--r--models/fixtures/foreign_reference.yml1
-rw-r--r--models/foreignreference/error.go43
-rw-r--r--models/foreignreference/foreignreference.go32
-rw-r--r--models/issue.go59
-rw-r--r--models/issue_test.go34
-rw-r--r--models/migrate.go7
-rw-r--r--models/migrate_test.go12
-rw-r--r--models/migrations/migrations.go2
-rw-r--r--models/migrations/v211.go26
9 files changed, 211 insertions, 5 deletions
diff --git a/models/fixtures/foreign_reference.yml b/models/fixtures/foreign_reference.yml
new file mode 100644
index 0000000000..ca780a73aa
--- /dev/null
+++ b/models/fixtures/foreign_reference.yml
@@ -0,0 +1 @@
+[] # empty
diff --git a/models/foreignreference/error.go b/models/foreignreference/error.go
new file mode 100644
index 0000000000..d783a08730
--- /dev/null
+++ b/models/foreignreference/error.go
@@ -0,0 +1,43 @@
+// Copyright 2022 Gitea. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package foreignreference
+
+import (
+ "fmt"
+)
+
+// ErrLocalIndexNotExist represents a "LocalIndexNotExist" kind of error.
+type ErrLocalIndexNotExist struct {
+ RepoID int64
+ ForeignIndex int64
+ Type string
+}
+
+// ErrLocalIndexNotExist checks if an error is a ErrLocalIndexNotExist.
+func IsErrLocalIndexNotExist(err error) bool {
+ _, ok := err.(ErrLocalIndexNotExist)
+ return ok
+}
+
+func (err ErrLocalIndexNotExist) Error() string {
+ return fmt.Sprintf("repository %d has no LocalIndex for ForeignIndex %d of type %s", err.RepoID, err.ForeignIndex, err.Type)
+}
+
+// ErrForeignIndexNotExist represents a "ForeignIndexNotExist" kind of error.
+type ErrForeignIndexNotExist struct {
+ RepoID int64
+ LocalIndex int64
+ Type string
+}
+
+// ErrForeignIndexNotExist checks if an error is a ErrForeignIndexNotExist.
+func IsErrForeignIndexNotExist(err error) bool {
+ _, ok := err.(ErrForeignIndexNotExist)
+ return ok
+}
+
+func (err ErrForeignIndexNotExist) Error() string {
+ return fmt.Sprintf("repository %d has no ForeignIndex for LocalIndex %d of type %s", err.RepoID, err.LocalIndex, err.Type)
+}
diff --git a/models/foreignreference/foreignreference.go b/models/foreignreference/foreignreference.go
new file mode 100644
index 0000000000..cc657a0fbe
--- /dev/null
+++ b/models/foreignreference/foreignreference.go
@@ -0,0 +1,32 @@
+// Copyright 2022 Gitea. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package foreignreference
+
+import (
+ "code.gitea.io/gitea/models/db"
+)
+
+// Type* are valid values for the Type field of ForeignReference
+const (
+ TypeIssue = "issue"
+ TypePullRequest = "pull_request"
+ TypeComment = "comment"
+ TypeReview = "review"
+ TypeReviewComment = "review_comment"
+ TypeRelease = "release"
+)
+
+// ForeignReference represents external references
+type ForeignReference struct {
+ // RepoID is the first column in all indices. now we only need 2 indices: (repo, local) and (repo, foreign, type)
+ RepoID int64 `xorm:"UNIQUE(repo_foreign_type) INDEX(repo_local)" `
+ LocalIndex int64 `xorm:"INDEX(repo_local)"` // the resource key inside Gitea, it can be IssueIndex, or some model ID.
+ ForeignIndex string `xorm:"INDEX UNIQUE(repo_foreign_type)"`
+ Type string `xorm:"VARCHAR(16) INDEX UNIQUE(repo_foreign_type)"`
+}
+
+func init() {
+ db.RegisterModel(new(ForeignReference))
+}
diff --git a/models/issue.go b/models/issue.go
index fd59ac0a4b..ed94195ed1 100644
--- a/models/issue.go
+++ b/models/issue.go
@@ -15,6 +15,7 @@ import (
admin_model "code.gitea.io/gitea/models/admin"
"code.gitea.io/gitea/models/db"
+ "code.gitea.io/gitea/models/foreignreference"
"code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo"
@@ -67,11 +68,12 @@ type Issue struct {
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
- Attachments []*repo_model.Attachment `xorm:"-"`
- Comments []*Comment `xorm:"-"`
- Reactions ReactionList `xorm:"-"`
- TotalTrackedTime int64 `xorm:"-"`
- Assignees []*user_model.User `xorm:"-"`
+ Attachments []*repo_model.Attachment `xorm:"-"`
+ Comments []*Comment `xorm:"-"`
+ Reactions ReactionList `xorm:"-"`
+ TotalTrackedTime int64 `xorm:"-"`
+ Assignees []*user_model.User `xorm:"-"`
+ ForeignReference *foreignreference.ForeignReference `xorm:"-"`
// IsLocked limits commenting abilities to users on an issue
// with write access
@@ -271,6 +273,29 @@ func (issue *Issue) loadReactions(ctx context.Context) (err error) {
return nil
}
+func (issue *Issue) loadForeignReference(ctx context.Context) (err error) {
+ if issue.ForeignReference != nil {
+ return nil
+ }
+ reference := &foreignreference.ForeignReference{
+ RepoID: issue.RepoID,
+ LocalIndex: issue.Index,
+ Type: foreignreference.TypeIssue,
+ }
+ has, err := db.GetEngine(ctx).Get(reference)
+ if err != nil {
+ return err
+ } else if !has {
+ return foreignreference.ErrForeignIndexNotExist{
+ RepoID: issue.RepoID,
+ LocalIndex: issue.Index,
+ Type: foreignreference.TypeIssue,
+ }
+ }
+ issue.ForeignReference = reference
+ return nil
+}
+
func (issue *Issue) loadMilestone(e db.Engine) (err error) {
if (issue.Milestone == nil || issue.Milestone.ID != issue.MilestoneID) && issue.MilestoneID > 0 {
issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
@@ -332,6 +357,10 @@ func (issue *Issue) loadAttributes(ctx context.Context) (err error) {
}
}
+ if err = issue.loadForeignReference(ctx); err != nil && !foreignreference.IsErrForeignIndexNotExist(err) {
+ return err
+ }
+
return issue.loadReactions(ctx)
}
@@ -1110,6 +1139,26 @@ func GetIssueByIndex(repoID, index int64) (*Issue, error) {
return issue, nil
}
+// GetIssueByForeignIndex returns raw issue by foreign ID
+func GetIssueByForeignIndex(ctx context.Context, repoID, foreignIndex int64) (*Issue, error) {
+ reference := &foreignreference.ForeignReference{
+ RepoID: repoID,
+ ForeignIndex: strconv.FormatInt(foreignIndex, 10),
+ Type: foreignreference.TypeIssue,
+ }
+ has, err := db.GetEngine(ctx).Get(reference)
+ if err != nil {
+ return nil, err
+ } else if !has {
+ return nil, foreignreference.ErrLocalIndexNotExist{
+ RepoID: repoID,
+ ForeignIndex: foreignIndex,
+ Type: foreignreference.TypeIssue,
+ }
+ }
+ return GetIssueByIndex(repoID, reference.LocalIndex)
+}
+
// GetIssueWithAttrsByIndex returns issue by index in a repository.
func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
issue, err := GetIssueByIndex(repoID, index)
diff --git a/models/issue_test.go b/models/issue_test.go
index 7cc0aa61b0..9afbce67c1 100644
--- a/models/issue_test.go
+++ b/models/issue_test.go
@@ -8,11 +8,13 @@ import (
"context"
"fmt"
"sort"
+ "strconv"
"sync"
"testing"
"time"
"code.gitea.io/gitea/models/db"
+ "code.gitea.io/gitea/models/foreignreference"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -534,3 +536,35 @@ func TestCorrectIssueStats(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, issueStats.OpenCount, issueAmount)
}
+
+func TestIssueForeignReference(t *testing.T) {
+ assert.NoError(t, unittest.PrepareTestDatabase())
+ issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 4}).(*Issue)
+ assert.NotEqualValues(t, issue.Index, issue.ID) // make sure they are different to avoid false positive
+
+ // it is fine for an issue to not have a foreign reference
+ err := issue.LoadAttributes()
+ assert.NoError(t, err)
+ assert.Nil(t, issue.ForeignReference)
+
+ var foreignIndex int64 = 12345
+ _, err = GetIssueByForeignIndex(context.Background(), issue.RepoID, foreignIndex)
+ assert.True(t, foreignreference.IsErrLocalIndexNotExist(err))
+
+ _, err = db.GetEngine(db.DefaultContext).Insert(&foreignreference.ForeignReference{
+ LocalIndex: issue.Index,
+ ForeignIndex: strconv.FormatInt(foreignIndex, 10),
+ RepoID: issue.RepoID,
+ Type: foreignreference.TypeIssue,
+ })
+ assert.NoError(t, err)
+
+ err = issue.LoadAttributes()
+ assert.NoError(t, err)
+
+ assert.EqualValues(t, issue.ForeignReference.ForeignIndex, strconv.FormatInt(foreignIndex, 10))
+
+ found, err := GetIssueByForeignIndex(context.Background(), issue.RepoID, foreignIndex)
+ assert.NoError(t, err)
+ assert.EqualValues(t, found.Index, issue.Index)
+}
diff --git a/models/migrate.go b/models/migrate.go
index bbfba1fa1e..2470fd4336 100644
--- a/models/migrate.go
+++ b/models/migrate.go
@@ -83,6 +83,13 @@ func insertIssue(ctx context.Context, issue *Issue) error {
}
}
+ if issue.ForeignReference != nil {
+ issue.ForeignReference.LocalIndex = issue.Index
+ if _, err := sess.Insert(issue.ForeignReference); err != nil {
+ return err
+ }
+ }
+
return nil
}
diff --git a/models/migrate_test.go b/models/migrate_test.go
index d85dcbfeef..f4af7ffe37 100644
--- a/models/migrate_test.go
+++ b/models/migrate_test.go
@@ -5,8 +5,10 @@
package models
import (
+ "strconv"
"testing"
+ "code.gitea.io/gitea/models/foreignreference"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -45,6 +47,7 @@ func assertCreateIssues(t *testing.T, isPull bool) {
UserID: owner.ID,
}
+ foreignIndex := int64(12345)
title := "issuetitle1"
is := &Issue{
RepoID: repo.ID,
@@ -58,11 +61,20 @@ func assertCreateIssues(t *testing.T, isPull bool) {
IsClosed: true,
Labels: []*Label{label},
Reactions: []*Reaction{reaction},
+ ForeignReference: &foreignreference.ForeignReference{
+ ForeignIndex: strconv.FormatInt(foreignIndex, 10),
+ RepoID: repo.ID,
+ Type: foreignreference.TypeIssue,
+ },
}
err := InsertIssues(is)
assert.NoError(t, err)
i := unittest.AssertExistsAndLoadBean(t, &Issue{Title: title}).(*Issue)
+ assert.Nil(t, i.ForeignReference)
+ err = i.LoadAttributes()
+ assert.NoError(t, err)
+ assert.EqualValues(t, strconv.FormatInt(foreignIndex, 10), i.ForeignReference.ForeignIndex)
unittest.AssertExistsAndLoadBean(t, &Reaction{Type: "heart", UserID: owner.ID, IssueID: i.ID})
}
diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go
index 31b172a68d..5ed358822b 100644
--- a/models/migrations/migrations.go
+++ b/models/migrations/migrations.go
@@ -373,6 +373,8 @@ var migrations = []Migration{
NewMigration("Increase WebAuthentication CredentialID size to 410 - NO-OPED", increaseCredentialIDTo410),
// v210 -> v211
NewMigration("v208 was completely broken - remigrate", remigrateU2FCredentials),
+ // v211 -> v212
+ NewMigration("Create ForeignReference table", createForeignReferenceTable),
}
// GetCurrentDBVersion returns the current db version
diff --git a/models/migrations/v211.go b/models/migrations/v211.go
new file mode 100644
index 0000000000..26ccfd2037
--- /dev/null
+++ b/models/migrations/v211.go
@@ -0,0 +1,26 @@
+// Copyright 2022 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package migrations
+
+import (
+ "fmt"
+
+ "xorm.io/xorm"
+)
+
+func createForeignReferenceTable(x *xorm.Engine) error {
+ type ForeignReference struct {
+ // RepoID is the first column in all indices. now we only need 2 indices: (repo, local) and (repo, foreign, type)
+ RepoID int64 `xorm:"UNIQUE(repo_foreign_type) INDEX(repo_local)" `
+ LocalIndex int64 `xorm:"INDEX(repo_local)"` // the resource key inside Gitea, it can be IssueIndex, or some model ID.
+ ForeignIndex string `xorm:"INDEX UNIQUE(repo_foreign_type)"`
+ Type string `xorm:"VARCHAR(16) INDEX UNIQUE(repo_foreign_type)"`
+ }
+
+ if err := x.Sync2(new(ForeignReference)); err != nil {
+ return fmt.Errorf("Sync2: %v", err)
+ }
+ return nil
+}