From 66b8a43e5f9bd82f0daa3e7cbcab859457c8064f Mon Sep 17 00:00:00 2001
From: Gusted <williamzijl7@hotmail.com>
Date: Mon, 14 Mar 2022 12:04:41 +0000
Subject: [PATCH] Refactor mirror code & fix `StartToMirror` (#18904) (#19075)

- Backport #18904.
---
 services/mirror/mirror.go | 30 +++++++++++++++++-------------
 1 file changed, 17 insertions(+), 13 deletions(-)

diff --git a/services/mirror/mirror.go b/services/mirror/mirror.go
index 4234457b0b..ac8d72906b 100644
--- a/services/mirror/mirror.go
+++ b/services/mirror/mirror.go
@@ -29,19 +29,23 @@ const (
 
 // SyncRequest for the mirror queue
 type SyncRequest struct {
-	Type   SyncType
-	RepoID int64
+	Type        SyncType
+	ReferenceID int64 // RepoID for pull mirror, MirrorID fro push mirror
 }
 
 // doMirrorSync causes this request to mirror itself
 func doMirrorSync(ctx context.Context, req *SyncRequest) {
+	if req.ReferenceID == 0 {
+		log.Warn("Skipping mirror sync request, no reference ID was specified")
+		return
+	}
 	switch req.Type {
 	case PushMirrorType:
-		_ = SyncPushMirror(ctx, req.RepoID)
+		_ = SyncPushMirror(ctx, req.ReferenceID)
 	case PullMirrorType:
-		_ = SyncPullMirror(ctx, req.RepoID)
+		_ = SyncPullMirror(ctx, req.ReferenceID)
 	default:
-		log.Error("Unknown Request type in queue: %v for RepoID[%d]", req.Type, req.RepoID)
+		log.Error("Unknown Request type in queue: %v for ReferenceID[%d]", req.Type, req.ReferenceID)
 	}
 }
 
@@ -67,8 +71,8 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error {
 			}
 			repo = m.Repo
 			item = SyncRequest{
-				Type:   PullMirrorType,
-				RepoID: m.RepoID,
+				Type:        PullMirrorType,
+				ReferenceID: m.RepoID,
 			}
 		} else if m, ok := bean.(*repo_model.PushMirror); ok {
 			if m.Repo == nil {
@@ -77,8 +81,8 @@ func Update(ctx context.Context, pullLimit, pushLimit int) error {
 			}
 			repo = m.Repo
 			item = SyncRequest{
-				Type:   PushMirrorType,
-				RepoID: m.RepoID,
+				Type:        PushMirrorType,
+				ReferenceID: m.ID,
 			}
 		} else {
 			log.Error("Unknown bean: %v", bean)
@@ -162,8 +166,8 @@ func StartToMirror(repoID int64) {
 	}
 	go func() {
 		err := mirrorQueue.Push(&SyncRequest{
-			Type:   PullMirrorType,
-			RepoID: repoID,
+			Type:        PullMirrorType,
+			ReferenceID: repoID,
 		})
 		if err != nil {
 			log.Error("Unable to push sync request for to the queue for push mirror repo[%d]: Error: %v", repoID, err)
@@ -178,8 +182,8 @@ func AddPushMirrorToQueue(mirrorID int64) {
 	}
 	go func() {
 		err := mirrorQueue.Push(&SyncRequest{
-			Type:   PushMirrorType,
-			RepoID: mirrorID,
+			Type:        PushMirrorType,
+			ReferenceID: mirrorID,
 		})
 		if err != nil {
 			log.Error("Unable to push sync request to the queue for pull mirror repo[%d]: Error: %v", mirrorID, err)