Skip to content

Exposed handler waiting time as configurable #38

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 16, 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
1 change: 1 addition & 0 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ LOG_LEVEL=DEBUG
MONGO_URI=mongodb://localhost:27017
MONGO_DB=switcher-gitops-test
GIT_TOKEN_PRIVATE_KEY=SecretSecretSecretSecretSecretSe
HANDLER_WAITING_TIME=1m

SWITCHER_API_URL=https://switcherapi.com/api
SWITCHER_API_JWT_SECRET=SecretSecretSecretSecretSecretSe
Expand Down
34 changes: 17 additions & 17 deletions src/controller/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import (
)

type AccountController struct {
CoreHandler *core.CoreHandler
AccountRepository repository.AccountRepository
RouteAccountPath string
coreHandler *core.CoreHandler
accountRepository repository.AccountRepository
routeAccountPath string
}

type ErrorResponse struct {
Expand All @@ -24,18 +24,18 @@ type ErrorResponse struct {

func NewAccountController(repo repository.AccountRepository, coreHandler *core.CoreHandler) *AccountController {
return &AccountController{
CoreHandler: coreHandler,
AccountRepository: repo,
RouteAccountPath: "/account",
coreHandler: coreHandler,
accountRepository: repo,
routeAccountPath: "/account",
}
}

func (controller *AccountController) RegisterRoutes(r *mux.Router) http.Handler {
r.NewRoute().Path(controller.RouteAccountPath).Name("CreateAccount").HandlerFunc(controller.CreateAccountHandler).Methods(http.MethodPost)
r.NewRoute().Path(controller.RouteAccountPath).Name("UpdateAccount").HandlerFunc(controller.UpdateAccountHandler).Methods(http.MethodPut)
r.NewRoute().Path(controller.RouteAccountPath + "/{domainId}").Name("GelAllAccountsByDomainId").HandlerFunc(controller.FetchAllAccountsByDomainIdHandler).Methods(http.MethodGet)
r.NewRoute().Path(controller.RouteAccountPath + "/{domainId}/{enviroment}").Name("GetAccount").HandlerFunc(controller.FetchAccountHandler).Methods(http.MethodGet)
r.NewRoute().Path(controller.RouteAccountPath + "/{domainId}/{enviroment}").Name("DeleteAccount").HandlerFunc(controller.DeleteAccountHandler).Methods(http.MethodDelete)
r.NewRoute().Path(controller.routeAccountPath).Name("CreateAccount").HandlerFunc(controller.CreateAccountHandler).Methods(http.MethodPost)
r.NewRoute().Path(controller.routeAccountPath).Name("UpdateAccount").HandlerFunc(controller.UpdateAccountHandler).Methods(http.MethodPut)
r.NewRoute().Path(controller.routeAccountPath + "/{domainId}").Name("GelAllAccountsByDomainId").HandlerFunc(controller.FetchAllAccountsByDomainIdHandler).Methods(http.MethodGet)
r.NewRoute().Path(controller.routeAccountPath + "/{domainId}/{enviroment}").Name("GetAccount").HandlerFunc(controller.FetchAccountHandler).Methods(http.MethodGet)
r.NewRoute().Path(controller.routeAccountPath + "/{domainId}/{enviroment}").Name("DeleteAccount").HandlerFunc(controller.DeleteAccountHandler).Methods(http.MethodDelete)

return r
}
Expand All @@ -53,7 +53,7 @@ func (controller *AccountController) CreateAccountHandler(w http.ResponseWriter,
accountRequest.Token = utils.Encrypt(accountRequest.Token, config.GetEnv("GIT_TOKEN_PRIVATE_KEY"))
}

accountCreated, err := controller.AccountRepository.Create(&accountRequest)
accountCreated, err := controller.accountRepository.Create(&accountRequest)
if err != nil {
utils.Log(utils.LogLevelError, "Error creating account: %s", err.Error())
utils.ResponseJSON(w, ErrorResponse{Error: "Error creating account"}, http.StatusInternalServerError)
Expand All @@ -62,7 +62,7 @@ func (controller *AccountController) CreateAccountHandler(w http.ResponseWriter,

// Initialize account handler
gitService := core.NewGitService(accountCreated.Repository, accountCreated.Token, accountCreated.Branch)
go controller.CoreHandler.StartAccountHandler(accountCreated.ID.Hex(), gitService)
go controller.coreHandler.StartAccountHandler(accountCreated.ID.Hex(), gitService)

utils.ResponseJSON(w, accountCreated, http.StatusCreated)
}
Expand All @@ -71,7 +71,7 @@ func (controller *AccountController) FetchAccountHandler(w http.ResponseWriter,
domainId := mux.Vars(r)["domainId"]
enviroment := mux.Vars(r)["enviroment"]

account, err := controller.AccountRepository.FetchByDomainIdEnvironment(domainId, enviroment)
account, err := controller.accountRepository.FetchByDomainIdEnvironment(domainId, enviroment)
if err != nil {
utils.Log(utils.LogLevelError, "Error fetching account: %s", err.Error())
utils.ResponseJSON(w, ErrorResponse{Error: "Account not found"}, http.StatusNotFound)
Expand All @@ -84,7 +84,7 @@ func (controller *AccountController) FetchAccountHandler(w http.ResponseWriter,
func (controller *AccountController) FetchAllAccountsByDomainIdHandler(w http.ResponseWriter, r *http.Request) {
domainId := mux.Vars(r)["domainId"]

accounts := controller.AccountRepository.FetchAllByDomainId(domainId)
accounts := controller.accountRepository.FetchAllByDomainId(domainId)
if accounts == nil {
utils.Log(utils.LogLevelError, "Not found accounts for domain: %s", domainId)
utils.ResponseJSON(w, ErrorResponse{Error: "Not found accounts for domain: " + domainId}, http.StatusNotFound)
Expand All @@ -108,7 +108,7 @@ func (controller *AccountController) UpdateAccountHandler(w http.ResponseWriter,
accountRequest.Token = utils.Encrypt(accountRequest.Token, config.GetEnv("GIT_TOKEN_PRIVATE_KEY"))
}

accountUpdated, err := controller.AccountRepository.Update(&accountRequest)
accountUpdated, err := controller.accountRepository.Update(&accountRequest)
if err != nil {
utils.Log(utils.LogLevelError, "Error updating account: %s", err.Error())
utils.ResponseJSON(w, ErrorResponse{Error: "Error updating account"}, http.StatusInternalServerError)
Expand All @@ -122,7 +122,7 @@ func (controller *AccountController) DeleteAccountHandler(w http.ResponseWriter,
domainId := mux.Vars(r)["domainId"]
enviroment := mux.Vars(r)["enviroment"]

err := controller.AccountRepository.DeleteByDomainIdEnvironment(domainId, enviroment)
err := controller.accountRepository.DeleteByDomainIdEnvironment(domainId, enviroment)
if err != nil {
utils.Log(utils.LogLevelError, "Error deleting account: %s", err.Error())
utils.ResponseJSON(w, ErrorResponse{Error: "Error deleting account: " + err.Error()}, http.StatusInternalServerError)
Expand Down
28 changes: 14 additions & 14 deletions src/controller/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestCreateAccountHandler(t *testing.T) {
// Test
accountV1.Domain.ID = "123-controller-create-account"
payload, _ := json.Marshal(accountV1)
req, _ := http.NewRequest(http.MethodPost, accountController.RouteAccountPath, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodPost, accountController.routeAccountPath, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -37,7 +37,7 @@ func TestCreateAccountHandler(t *testing.T) {
t.Run("Should not create an account - invalid request", func(t *testing.T) {
// Test
payload := []byte("")
req, _ := http.NewRequest(http.MethodPost, accountController.RouteAccountPath, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodPost, accountController.routeAccountPath, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -51,7 +51,7 @@ func TestCreateAccountHandler(t *testing.T) {

// Test
payload, _ := json.Marshal(accountV1)
req, _ := http.NewRequest(http.MethodPost, accountController.RouteAccountPath, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodPost, accountController.routeAccountPath, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -68,7 +68,7 @@ func TestFetchAccountHandler(t *testing.T) {

// Test
payload := []byte("")
req, _ := http.NewRequest(http.MethodGet, accountController.RouteAccountPath+"/"+accountV1.Domain.ID+"/"+accountV1.Environment, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodGet, accountController.routeAccountPath+"/"+accountV1.Domain.ID+"/"+accountV1.Environment, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -83,7 +83,7 @@ func TestFetchAccountHandler(t *testing.T) {
t.Run("Should not fetch an account by domain ID / environment - not found", func(t *testing.T) {
// Test
payload := []byte("")
req, _ := http.NewRequest(http.MethodGet, accountController.RouteAccountPath+"/not-found/default", bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodGet, accountController.routeAccountPath+"/not-found/default", bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -100,7 +100,7 @@ func TestFetchAccountHandler(t *testing.T) {

// Test
payload := []byte("")
req, _ := http.NewRequest(http.MethodGet, accountController.RouteAccountPath+"/"+accountV1.Domain.ID, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodGet, accountController.routeAccountPath+"/"+accountV1.Domain.ID, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -115,7 +115,7 @@ func TestFetchAccountHandler(t *testing.T) {
t.Run("Should not fetch all accounts by domain ID - not found", func(t *testing.T) {
// Test
payload := []byte("")
req, _ := http.NewRequest(http.MethodGet, accountController.RouteAccountPath+"/not-found", bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodGet, accountController.routeAccountPath+"/not-found", bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -138,7 +138,7 @@ func TestUpdateAccountHandler(t *testing.T) {

// Test
payload, _ := json.Marshal(accountV2)
req, _ := http.NewRequest(http.MethodPut, accountController.RouteAccountPath, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodPut, accountController.routeAccountPath, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -164,7 +164,7 @@ func TestUpdateAccountHandler(t *testing.T) {
accountRequest.Token = "new-token"

payload, _ := json.Marshal(accountRequest)
req, _ := http.NewRequest(http.MethodPut, accountController.RouteAccountPath, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodPut, accountController.routeAccountPath, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -185,7 +185,7 @@ func TestUpdateAccountHandler(t *testing.T) {
t.Run("Should not update an account - invalid request", func(t *testing.T) {
// Test
payload := []byte("")
req, _ := http.NewRequest(http.MethodPut, accountController.RouteAccountPath, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodPut, accountController.routeAccountPath, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -203,7 +203,7 @@ func TestUpdateAccountHandler(t *testing.T) {

// Test
payload, _ := json.Marshal(accountV1)
req, _ := http.NewRequest(http.MethodPut, accountController.RouteAccountPath, bytes.NewBuffer(payload))
req, _ := http.NewRequest(http.MethodPut, accountController.routeAccountPath, bytes.NewBuffer(payload))
response := executeRequest(req)

// Assert
Expand All @@ -219,7 +219,7 @@ func TestDeleteAccountHandler(t *testing.T) {
accountController.CreateAccountHandler(givenAccountRequest(accountV1))

// Test
req, _ := http.NewRequest(http.MethodDelete, accountController.RouteAccountPath+"/"+accountV1.Domain.ID+"/"+accountV1.Environment, nil)
req, _ := http.NewRequest(http.MethodDelete, accountController.routeAccountPath+"/"+accountV1.Domain.ID+"/"+accountV1.Environment, nil)
response := executeRequest(req)

// Assert
Expand All @@ -228,7 +228,7 @@ func TestDeleteAccountHandler(t *testing.T) {

t.Run("Should not delete an account by domain ID / environment - not found", func(t *testing.T) {
// Test
req, _ := http.NewRequest(http.MethodDelete, accountController.RouteAccountPath+"/not-found/default", nil)
req, _ := http.NewRequest(http.MethodDelete, accountController.routeAccountPath+"/not-found/default", nil)
response := executeRequest(req)

// Assert
Expand All @@ -241,7 +241,7 @@ func TestDeleteAccountHandler(t *testing.T) {

func givenAccountRequest(data model.Account) (*httptest.ResponseRecorder, *http.Request) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, accountController.RouteAccountPath, nil)
r := httptest.NewRequest(http.MethodPost, accountController.routeAccountPath, nil)

// Encode the account request as JSON
body, _ := json.Marshal(data)
Expand Down
12 changes: 6 additions & 6 deletions src/controller/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
)

type ApiController struct {
CoreHandler *core.CoreHandler
RouteCheckApiPath string
coreHandler *core.CoreHandler
routeCheckApiPath string
}

type ApiCheckResponse struct {
Expand All @@ -32,13 +32,13 @@ type ApiSettingsResponse struct {

func NewApiController(coreHandler *core.CoreHandler) *ApiController {
return &ApiController{
CoreHandler: coreHandler,
RouteCheckApiPath: "/api/check",
coreHandler: coreHandler,
routeCheckApiPath: "/api/check",
}
}

func (controller *ApiController) RegisterRoutes(r *mux.Router) http.Handler {
r.NewRoute().Path(controller.RouteCheckApiPath).Name("CheckApi").HandlerFunc(controller.CheckApiHandler).Methods(http.MethodGet)
r.NewRoute().Path(controller.routeCheckApiPath).Name("CheckApi").HandlerFunc(controller.CheckApiHandler).Methods(http.MethodGet)

return r
}
Expand All @@ -52,7 +52,7 @@ func (controller *ApiController) CheckApiHandler(w http.ResponseWriter, r *http.
SwitcherURL: config.GetEnv("SWITCHER_API_URL"),
SwitcherSecret: len(config.GetEnv("SWITCHER_API_JWT_SECRET")) > 0,
GitTokenSecret: len(config.GetEnv("GIT_TOKEN_PRIVATE_KEY")) > 0,
CoreHandlerStatus: controller.CoreHandler.Status,
CoreHandlerStatus: controller.coreHandler.Status,
NumGoroutines: runtime.NumGoroutine(),
},
}, http.StatusOK)
Expand Down
16 changes: 8 additions & 8 deletions src/core/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ type IAPIService interface {
}

type ApiService struct {
ApiKey string
ApiUrl string
apiKey string
apiUrl string
}

func NewApiService(apiKey string, apiUrl string) *ApiService {
return &ApiService{
ApiKey: apiKey,
ApiUrl: apiUrl,
apiKey: apiKey,
apiUrl: apiUrl,
}
}

Expand Down Expand Up @@ -70,7 +70,7 @@ func (a *ApiService) FetchSnapshot(domainId string, environment string) (string,

func (a *ApiService) ApplyChangesToAPI(domainId string, environment string, diff model.DiffResult) (ApplyChangeResponse, error) {
reqBody, _ := json.Marshal(diff)
responseBody, err := a.doPostRequest(a.ApiUrl+"/gitops/apply", domainId, reqBody)
responseBody, err := a.doPostRequest(a.apiUrl+"/gitops/apply", domainId, reqBody)

if err != nil {
return ApplyChangeResponse{}, err
Expand All @@ -83,11 +83,11 @@ func (a *ApiService) ApplyChangesToAPI(domainId string, environment string, diff

func (a *ApiService) doGraphQLRequest(domainId string, query string) (string, error) {
// Generate a bearer token
token := generateBearerToken(a.ApiKey, domainId)
token := generateBearerToken(a.apiKey, domainId)

// Create a new request
reqBody, _ := json.Marshal(GraphQLRequest{Query: query})
req, _ := http.NewRequest("POST", a.ApiUrl+"/gitops-graphql", bytes.NewBuffer(reqBody))
req, _ := http.NewRequest("POST", a.apiUrl+"/gitops-graphql", bytes.NewBuffer(reqBody))

// Set the request headers
setHeaders(req, token)
Expand All @@ -106,7 +106,7 @@ func (a *ApiService) doGraphQLRequest(domainId string, query string) (string, er

func (a *ApiService) doPostRequest(url string, domainId string, body []byte) (string, error) {
// Generate a bearer token
token := generateBearerToken(a.ApiKey, domainId)
token := generateBearerToken(a.apiKey, domainId)

// Create a new request
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(body))
Expand Down
24 changes: 12 additions & 12 deletions src/core/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,23 @@ type IGitService interface {
}

type GitService struct {
RepoURL string
EncryptedToken string
BranchName string
repoURL string
encryptedToken string
branchName string
}

func NewGitService(repoURL string, encryptedToken string, branchName string) *GitService {
return &GitService{
RepoURL: repoURL,
EncryptedToken: encryptedToken,
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
g.repoURL = repository
g.encryptedToken = encryptedToken
g.branchName = branch
}

func (g *GitService) GetRepositoryData(environment string) (*model.RepositoryData, error) {
Expand Down Expand Up @@ -140,14 +140,14 @@ func (g *GitService) getCommitObject() (*object.Commit, error) {

func (g *GitService) getRepository(fs billy.Filesystem) (*git.Repository, error) {
return git.Clone(memory.NewStorage(), fs, &git.CloneOptions{
URL: g.RepoURL,
ReferenceName: plumbing.NewBranchReferenceName(g.BranchName),
URL: g.repoURL,
ReferenceName: plumbing.NewBranchReferenceName(g.branchName),
Auth: g.getAuth(),
})
}

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

if err != nil || decryptedToken == "" {
return nil
Expand Down
12 changes: 6 additions & 6 deletions src/core/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ func TestNewGitService(t *testing.T) {
gitService := NewGitService(repoURL, encryptedToken, branchName)

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

func TestUpdateRepositorySettings(t *testing.T) {
Expand All @@ -45,9 +45,9 @@ func TestUpdateRepositorySettings(t *testing.T) {
gitService.UpdateRepositorySettings("newRepoURL", "newEncryptedToken", "newBranch")

// Assert
assert.Equal(t, "newRepoURL", gitService.RepoURL)
assert.Equal(t, "newEncryptedToken", gitService.EncryptedToken)
assert.Equal(t, "newBranch", gitService.BranchName)
assert.Equal(t, "newRepoURL", gitService.repoURL)
assert.Equal(t, "newEncryptedToken", gitService.encryptedToken)
assert.Equal(t, "newBranch", gitService.branchName)
}

func TestGetRepositoryData(t *testing.T) {
Expand Down
Loading
Loading