Skip to content

Moved GitService initialization to StartAccountHandler #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .env.test
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
PORT=8000
MONGO_URI=mongodb://localhost:27017
MONGO_DB=switcher-gitops-test
GIT_TOKEN_PRIVATE_KEY=
GIT_TOKEN_PRIVATE_KEY=SecretSecretSecretSecretSecretSe

SWITCHER_API_URL=https://switcherapi.com/api
SWITCHER_API_JWT_SECRET=
SWITCHER_API_JWT_SECRET=SecretSecretSecretSecretSecretSe

# Only for testing purposes. Values are loaded from accounts
GIT_USER=
Expand Down
6 changes: 3 additions & 3 deletions src/core/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,9 @@ func setup() {
mongoDb = db.InitDb()

accountRepository := repository.NewAccountRepositoryMongo(mongoDb)
gitService := NewGitService("repoURL", "token", "main")
apiService := NewApiService("apiKey", "")
comparatorService := NewComparatorService()
coreHandler = NewCoreHandler(accountRepository, gitService, apiService, comparatorService)
coreHandler = NewCoreHandler(accountRepository, apiService, comparatorService)
}

func shutdown() {
Expand Down Expand Up @@ -65,8 +64,9 @@ func AssertContains(t *testing.T, actual string, expected string) {

func givenAccount() model.Account {
return model.Account{
Repository: "switcherapi/switcher-gitops",
Repository: "https://github.com/switcherapi/switcher-gitops-fixture",
Branch: "master",
Token: "token",
Environment: "default",
Domain: model.DomainDetails{
ID: "123-core-test",
Expand Down
30 changes: 22 additions & 8 deletions src/core/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,35 @@ import (
"github.com/go-git/go-git/v5/storage/memory"
"github.com/switcherapi/switcher-gitops/src/config"
"github.com/switcherapi/switcher-gitops/src/model"
"github.com/switcherapi/switcher-gitops/src/utils"
)

type IGitService interface {
GetRepositoryData(environment string) (*model.RepositoryData, error)
PushChanges(environment string, content string) (string, error)
UpdateRepositorySettings(repository string, encryptedToken string, branch string)
}

type GitService struct {
RepoURL string
Token string
BranchName string
RepoURL string
EncryptedToken string
BranchName string
}

func NewGitService(repoURL string, token string, branchName string) *GitService {
func NewGitService(repoURL string, encryptedToken string, branchName string) *GitService {
return &GitService{
RepoURL: repoURL,
Token: token,
BranchName: branchName,
RepoURL: repoURL,
EncryptedToken: encryptedToken,
BranchName: branchName,
}
}

func (g *GitService) UpdateRepositorySettings(repository string, encryptedToken string, branch string) {
g.RepoURL = repository
g.EncryptedToken = encryptedToken
g.BranchName = branch
}

func (g *GitService) GetRepositoryData(environment string) (*model.RepositoryData, error) {
commitHash, commitDate, content, err := g.getLastCommitData(model.FilePath + environment + ".json")

Expand Down Expand Up @@ -139,8 +147,14 @@ func (g *GitService) getRepository(fs billy.Filesystem) (*git.Repository, error)
}

func (g *GitService) getAuth() *http.BasicAuth {
decryptedToken, err := utils.Decrypt(g.EncryptedToken, config.GetEnv("GIT_TOKEN_PRIVATE_KEY"))

if err != nil || decryptedToken == "" {
return nil
}

return &http.BasicAuth{
Username: config.GetEnv("GIT_USER"),
Password: g.Token,
Password: decryptedToken,
}
}
101 changes: 56 additions & 45 deletions src/core/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/go-git/go-git/v5/storage/memory"
"github.com/stretchr/testify/assert"
appConfig "github.com/switcherapi/switcher-gitops/src/config"
"github.com/switcherapi/switcher-gitops/src/utils"
)

const (
Expand All @@ -21,75 +22,85 @@ const (
func TestNewGitService(t *testing.T) {
// Given
repoURL := "repoURL"
token := "token"
encryptedToken := "encryptedToken"
branchName := "main"

// Test
gitService := NewGitService(repoURL, token, branchName)
gitService := NewGitService(repoURL, encryptedToken, branchName)

// Assert
assert.Equal(t, repoURL, gitService.RepoURL)
assert.Equal(t, token, gitService.Token)
assert.Equal(t, encryptedToken, gitService.EncryptedToken)
assert.Equal(t, branchName, gitService.BranchName)
}

func TestGetRepositoryData(t *testing.T) {
if !canRunIntegratedTests() {
t.Skip(SkipMessage)
}

func TestUpdateRepositorySettings(t *testing.T) {
// Given
gitService := NewGitService(
appConfig.GetEnv("GIT_REPO_URL"),
appConfig.GetEnv("GIT_TOKEN"),
appConfig.GetEnv("GIT_BRANCH"))
repoURL := "repoURL"
encryptedToken := "encryptedToken"
branchName := "main"
gitService := NewGitService(repoURL, encryptedToken, branchName)

// Test
repositoryData, err := gitService.GetRepositoryData("default")
gitService.UpdateRepositorySettings("newRepoURL", "newEncryptedToken", "newBranch")

// Assert
assert.Nil(t, err)
assert.NotEmpty(t, repositoryData.CommitHash)
assert.NotEmpty(t, repositoryData.CommitDate)
assert.NotEmpty(t, repositoryData.Content)
assert.Equal(t, "newRepoURL", gitService.RepoURL)
assert.Equal(t, "newEncryptedToken", gitService.EncryptedToken)
assert.Equal(t, "newBranch", gitService.BranchName)
}

func TestGetRepositoryDataErrorInvalidEnvironment(t *testing.T) {
func TestGetRepositoryData(t *testing.T) {
if !canRunIntegratedTests() {
t.Skip(SkipMessage)
}

// Given
gitService := NewGitService(
appConfig.GetEnv("GIT_REPO_URL"),
appConfig.GetEnv("GIT_TOKEN"),
appConfig.GetEnv("GIT_BRANCH"))
t.Run("Should get repository data", func(t *testing.T) {
// Given
gitService := NewGitService(
appConfig.GetEnv("GIT_REPO_URL"),
utils.Encrypt(appConfig.GetEnv("GIT_TOKEN"), appConfig.GetEnv("GIT_TOKEN_PRIVATE_KEY")),
appConfig.GetEnv("GIT_BRANCH"))

// Test
repositoryData, err := gitService.GetRepositoryData("invalid")
// Test
repositoryData, err := gitService.GetRepositoryData("default")

// Assert
assert.NotNil(t, err)
assert.Nil(t, repositoryData)
}
// Assert
assert.Nil(t, err)
assert.NotEmpty(t, repositoryData.CommitHash)
assert.NotEmpty(t, repositoryData.CommitDate)
assert.NotEmpty(t, repositoryData.Content)
})

func TestGetRepositoryDataErrorInvalidToken(t *testing.T) {
if !canRunIntegratedTests() {
t.Skip(SkipMessage)
}
t.Run("Should not get repository data - invalid environment", func(t *testing.T) {
// Given
gitService := NewGitService(
appConfig.GetEnv("GIT_REPO_URL"),
utils.Encrypt(appConfig.GetEnv("GIT_TOKEN"), appConfig.GetEnv("GIT_TOKEN_PRIVATE_KEY")),
appConfig.GetEnv("GIT_BRANCH"))

// Given
gitService := NewGitService(
appConfig.GetEnv("GIT_REPO_URL"),
"invalid",
appConfig.GetEnv("GIT_BRANCH"))
// Test
repositoryData, err := gitService.GetRepositoryData("invalid")

// Test
repositoryData, err := gitService.GetRepositoryData("default")
// Assert
assert.NotNil(t, err)
assert.Nil(t, repositoryData)
})

// Assert
assert.NotNil(t, err)
assert.Nil(t, repositoryData)
t.Run("Should not get repository data - invalid token", func(t *testing.T) {
// Given
gitService := NewGitService(
appConfig.GetEnv("GIT_REPO_URL"),
"invalid",
appConfig.GetEnv("GIT_BRANCH"))

// Test
repositoryData, err := gitService.GetRepositoryData("default")

// Assert
assert.NotNil(t, err)
assert.Nil(t, repositoryData)
})
}

func TestPushChanges(t *testing.T) {
Expand All @@ -103,7 +114,7 @@ func TestPushChanges(t *testing.T) {
createBranch(branchName)
gitService := NewGitService(
appConfig.GetEnv("GIT_REPO_URL"),
appConfig.GetEnv("GIT_TOKEN"),
utils.Encrypt(appConfig.GetEnv("GIT_TOKEN"), appConfig.GetEnv("GIT_TOKEN_PRIVATE_KEY")),
branchName)

// Test
Expand All @@ -125,7 +136,7 @@ func TestPushChanges(t *testing.T) {
// Given
gitService := NewGitService(
appConfig.GetEnv("GIT_REPO_URL"),
appConfig.GetEnv("GIT_TOKEN_READ_ONLY"),
utils.Encrypt(appConfig.GetEnv("GIT_TOKEN_READ_ONLY"), appConfig.GetEnv("GIT_TOKEN_PRIVATE_KEY")),
appConfig.GetEnv("GIT_BRANCH"))

// Test
Expand Down
27 changes: 16 additions & 11 deletions src/core/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,14 @@ import (

type CoreHandler struct {
AccountRepository repository.AccountRepository
GitService IGitService
ApiService IAPIService
ComparatorService IComparatorService
status int
}

func NewCoreHandler(repo repository.AccountRepository, gitService IGitService, apiService IAPIService, comparatorService IComparatorService) *CoreHandler {
func NewCoreHandler(repo repository.AccountRepository, apiService IAPIService, comparatorService IComparatorService) *CoreHandler {
return &CoreHandler{
AccountRepository: repo,
GitService: gitService,
ApiService: apiService,
ComparatorService: comparatorService,
}
Expand All @@ -31,15 +29,19 @@ func (c *CoreHandler) InitCoreHandlerCoroutine() (int, error) {

// Iterate over accounts and start account handlers
for _, account := range accounts {
go c.StartAccountHandler(account.ID.Hex())
go c.StartAccountHandler(account.ID.Hex(), NewGitService(
account.Repository,
account.Token,
account.Branch,
))
}

// Update core handler status
c.status = 1
return c.status, nil
}

func (c *CoreHandler) StartAccountHandler(accountId string) {
func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitService) {
for {
// Fetch account
account, _ := c.AccountRepository.FetchByAccountId(accountId)
Expand All @@ -56,12 +58,15 @@ func (c *CoreHandler) StartAccountHandler(accountId string) {
continue
}

// Refresh account repository settings
gitService.UpdateRepositorySettings(account.Repository, account.Token, account.Branch)

// Fetch repository data
repositoryData, err := c.GitService.GetRepositoryData(account.Environment)
repositoryData, err := gitService.GetRepositoryData(account.Environment)

// Check if repository is out of sync
if err == nil && isRepositoryOutSync(*account, repositoryData.CommitHash) {
c.syncUp(*account, repositoryData)
c.syncUp(*account, repositoryData, gitService)
}

// Wait for the next cycle
Expand All @@ -70,7 +75,7 @@ func (c *CoreHandler) StartAccountHandler(accountId string) {
}
}

func (c *CoreHandler) syncUp(account model.Account, repositoryData *model.RepositoryData) {
func (c *CoreHandler) syncUp(account model.Account, repositoryData *model.RepositoryData, gitService IGitService) {
// Update account status: Out of sync
account.Domain.LastCommit = repositoryData.CommitHash
account.Domain.LastDate = repositoryData.CommitDate
Expand All @@ -88,7 +93,7 @@ func (c *CoreHandler) syncUp(account model.Account, repositoryData *model.Reposi
changeSource := ""
if snapshotApi.Domain.Version > account.Domain.Version {
changeSource = "Repository"
account, err = c.applyChangesToRepository(account, snapshotApi)
account, err = c.applyChangesToRepository(account, snapshotApi, gitService)
} else if len(diff.Changes) > 0 {
changeSource = "API"
account = c.applyChangesToAPI(account, repositoryData)
Expand Down Expand Up @@ -142,12 +147,12 @@ func (c *CoreHandler) applyChangesToAPI(account model.Account, repositoryData *m
return account
}

func (c *CoreHandler) applyChangesToRepository(account model.Account, snapshot model.Snapshot) (model.Account, error) {
func (c *CoreHandler) applyChangesToRepository(account model.Account, snapshot model.Snapshot, gitService IGitService) (model.Account, error) {
// Remove version from domain
snapshotContent := snapshot
snapshotContent.Domain.Version = ""

lastCommit, err := c.GitService.PushChanges(account.Environment, utils.ToJsonFromObject(snapshotContent))
lastCommit, err := gitService.PushChanges(account.Environment, utils.ToJsonFromObject(snapshotContent))

// Update domain
account.Domain.Version = snapshot.Domain.Version
Expand Down
Loading