Skip to content

Commit 9168c56

Browse files
authored
Integrated handler with API to push changes (#40)
1 parent 383beb8 commit 9168c56

File tree

4 files changed

+222
-152
lines changed

4 files changed

+222
-152
lines changed

src/core/api.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,15 @@ type GraphQLRequest struct {
1616
Query string `json:"query"`
1717
}
1818

19-
type ApplyChangeResponse struct {
19+
type PushChangeResponse struct {
2020
Message string `json:"message"`
2121
Version int `json:"version"`
2222
}
2323

2424
type IAPIService interface {
2525
FetchSnapshotVersion(domainId string, environment string) (string, error)
2626
FetchSnapshot(domainId string, environment string) (string, error)
27-
ApplyChangesToAPI(domainId string, environment string, diff model.DiffResult) (ApplyChangeResponse, error)
27+
PushChanges(domainId string, environment string, diff model.DiffResult) (PushChangeResponse, error)
2828
NewDataFromJson(jsonData []byte) model.Data
2929
}
3030

@@ -68,15 +68,15 @@ func (a *ApiService) FetchSnapshot(domainId string, environment string) (string,
6868
return responseBody, nil
6969
}
7070

71-
func (a *ApiService) ApplyChangesToAPI(domainId string, environment string, diff model.DiffResult) (ApplyChangeResponse, error) {
71+
func (a *ApiService) PushChanges(domainId string, environment string, diff model.DiffResult) (PushChangeResponse, error) {
7272
reqBody, _ := json.Marshal(diff)
73-
responseBody, err := a.doPostRequest(a.apiUrl+"/gitops/apply", domainId, reqBody)
73+
responseBody, err := a.doPostRequest(a.apiUrl+"/gitops/push", domainId, reqBody)
7474

7575
if err != nil {
76-
return ApplyChangeResponse{}, err
76+
return PushChangeResponse{}, err
7777
}
7878

79-
var response ApplyChangeResponse
79+
var response PushChangeResponse
8080
json.Unmarshal([]byte(responseBody), &response)
8181
return response, nil
8282
}

src/core/api_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,8 @@ func TestFetchSnapshot(t *testing.T) {
113113
})
114114
}
115115

116-
func TestApplyChangesToAPI(t *testing.T) {
117-
t.Run("Should apply changes to API", func(t *testing.T) {
116+
func TestPushChangesToAPI(t *testing.T) {
117+
t.Run("Should push changes to API", func(t *testing.T) {
118118
// Given
119119
diff := givenDiffResult()
120120
fakeApiServer := givenApiResponse(http.StatusOK, `{
@@ -126,7 +126,7 @@ func TestApplyChangesToAPI(t *testing.T) {
126126
apiService := NewApiService(SWITCHER_API_JWT_SECRET, fakeApiServer.URL)
127127

128128
// Test
129-
response, _ := apiService.ApplyChangesToAPI("domainId", "default", diff)
129+
response, _ := apiService.PushChanges("domainId", "default", diff)
130130

131131
// Assert
132132
assert.NotNil(t, response)
@@ -143,7 +143,7 @@ func TestApplyChangesToAPI(t *testing.T) {
143143
apiService := NewApiService("[INVALID_KEY]", fakeApiServer.URL)
144144

145145
// Test
146-
response, _ := apiService.ApplyChangesToAPI("domainId", "default", diff)
146+
response, _ := apiService.PushChanges("domainId", "default", diff)
147147

148148
// Assert
149149
assert.NotNil(t, response)
@@ -156,7 +156,7 @@ func TestApplyChangesToAPI(t *testing.T) {
156156
apiService := NewApiService("[SWITCHER_API_JWT_SECRET]", "http://localhost:8080")
157157

158158
// Test
159-
_, err := apiService.ApplyChangesToAPI("domainId", "default", diff)
159+
_, err := apiService.PushChanges("domainId", "default", diff)
160160

161161
// Assert
162162
assert.NotNil(t, err)

src/core/handler.go

Lines changed: 40 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package core
22

33
import (
4-
"fmt"
54
"time"
65

76
"github.com/switcherapi/switcher-gitops/src/config"
@@ -24,7 +23,8 @@ type CoreHandler struct {
2423
Status int
2524
}
2625

27-
func NewCoreHandler(accountRepository repository.AccountRepository, apiService IAPIService, comparatorService IComparatorService) *CoreHandler {
26+
func NewCoreHandler(accountRepository repository.AccountRepository, apiService IAPIService,
27+
comparatorService IComparatorService) *CoreHandler {
2828
timeWindow, unitWindow := utils.GetTimeWindow(config.GetEnv("HANDLER_WAITING_TIME"))
2929
waitingTime := time.Duration(timeWindow) * unitWindow
3030

@@ -78,10 +78,8 @@ func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitServi
7878

7979
// Wait for account to be active
8080
if !account.Settings.Active {
81-
utils.LogInfo("[%s - %s (%s)] Account is not active, waiting for activation",
82-
accountId, account.Domain.Name, account.Environment)
83-
84-
c.updateDomainStatus(*account, model.StatusPending, "Account was deactivated")
81+
c.updateDomainStatus(*account, model.StatusPending, "Account was deactivated",
82+
utils.LogLevelInfo)
8583
time.Sleep(time.Duration(c.waitingTime))
8684
continue
8785
}
@@ -93,10 +91,8 @@ func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitServi
9391
repositoryData, err := gitService.GetRepositoryData(account.Environment)
9492

9593
if err != nil {
96-
utils.LogError("[%s - %s (%s)] Failed to fetch repository data - %s",
97-
accountId, account.Domain.Name, account.Environment, err.Error())
98-
99-
c.updateDomainStatus(*account, model.StatusError, "Failed to fetch repository data - "+err.Error())
94+
c.updateDomainStatus(*account, model.StatusError, "Failed to fetch repository data - "+err.Error(),
95+
utils.LogLevelError)
10096
time.Sleep(time.Duration(c.waitingTime))
10197
continue
10298
}
@@ -105,10 +101,8 @@ func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitServi
105101
snapshotVersionPayload, err := c.apiService.FetchSnapshotVersion(account.Domain.ID, account.Environment)
106102

107103
if err != nil {
108-
utils.LogError("[%s - %s (%s)] Failed to fetch snapshot version - %s",
109-
accountId, account.Domain.Name, account.Environment, err.Error())
110-
111-
c.updateDomainStatus(*account, model.StatusError, "Failed to fetch snapshot version - "+err.Error())
104+
c.updateDomainStatus(*account, model.StatusError, "Failed to fetch snapshot version - "+err.Error(),
105+
utils.LogLevelError)
112106
time.Sleep(time.Duration(c.waitingTime))
113107
continue
114108
}
@@ -125,37 +119,31 @@ func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitServi
125119
}
126120

127121
func (c *CoreHandler) syncUp(account model.Account, repositoryData *model.RepositoryData, gitService IGitService) {
128-
utils.LogInfo("[%s - %s (%s)] Syncing up", account.ID.Hex(), account.Domain.Name, account.Environment)
129-
130122
// Update account status: Out of sync
131123
account.Domain.LastCommit = repositoryData.CommitHash
132124
account.Domain.LastDate = repositoryData.CommitDate
133-
c.updateDomainStatus(account, model.StatusOutSync, model.MessageSyncingUp)
125+
c.updateDomainStatus(account, model.StatusOutSync, model.MessageSyncingUp, utils.LogLevelInfo)
134126

135127
// Check for changes
136128
diff, snapshotApi, err := c.checkForChanges(account, repositoryData.Content)
137129

138130
if err != nil {
139-
utils.LogError("[%s - %s (%s)] Failed to check for changes - %s",
140-
account.ID.Hex(), account.Domain.Name, account.Environment, err.Error())
141-
142-
c.updateDomainStatus(account, model.StatusError, "Failed to check for changes - "+err.Error())
131+
c.updateDomainStatus(account, model.StatusError, "Failed to check for changes - "+err.Error(),
132+
utils.LogLevelError)
143133
return
144134
}
145135

146-
// Apply changes
147-
changeSource, account, err := c.applyChanges(snapshotApi, account, repositoryData, diff, gitService)
136+
// Push changes
137+
changeSource, account, err := c.pushChanges(snapshotApi, account, repositoryData, diff, gitService)
148138

149139
if err != nil {
150-
utils.LogError("[%s - %s (%s)] Failed to apply changes [%s] - %s",
151-
account.ID.Hex(), account.Domain.Name, account.Environment, changeSource, err.Error())
152-
153-
c.updateDomainStatus(account, model.StatusError, "Failed to apply changes ["+changeSource+"] - "+err.Error())
140+
c.updateDomainStatus(account, model.StatusError, "Failed to push changes ["+changeSource+"] - "+err.Error(),
141+
utils.LogLevelError)
154142
return
155143
}
156144

157145
// Update account status: Synced
158-
c.updateDomainStatus(account, model.StatusSynced, model.MessageSynced)
146+
c.updateDomainStatus(account, model.StatusSynced, model.MessageSynced, utils.LogLevelInfo)
159147
}
160148

161149
func (c *CoreHandler) checkForChanges(account model.Account, content string) (model.DiffResult, model.Snapshot, error) {
@@ -182,18 +170,15 @@ func (c *CoreHandler) checkForChanges(account model.Account, content string) (mo
182170
return c.comparatorService.MergeResults([]model.DiffResult{diffNew, diffChanged, diffDeleted}), snapshotApi.Snapshot, nil
183171
}
184172

185-
func (c *CoreHandler) applyChanges(snapshotApi model.Snapshot, account model.Account,
173+
func (c *CoreHandler) pushChanges(snapshotApi model.Snapshot, account model.Account,
186174
repositoryData *model.RepositoryData, diff model.DiffResult, gitService IGitService) (string, model.Account, error) {
187-
utils.LogDebug("[%s - %s (%s)] SnapshotAPI version: %s - SnapshotRepo version: %s",
188-
account.ID.Hex(), account.Domain.Name, account.Environment, fmt.Sprint(snapshotApi.Domain.Version), fmt.Sprint(account.Domain.Version))
189-
190175
err := error(nil)
191176

192177
changeSource := ""
193178
if snapshotApi.Domain.Version > account.Domain.Version {
194179
changeSource = "Repository"
195180
if c.isRepositoryOutSync(repositoryData, diff) {
196-
account, err = c.applyChangesToRepository(account, snapshotApi, gitService)
181+
account, err = c.pushChangesToRepository(account, snapshotApi, gitService)
197182
} else {
198183
utils.LogInfo("[%s - %s (%s)] Repository is up to date",
199184
account.ID.Hex(), account.Domain.Name, account.Environment)
@@ -202,36 +187,45 @@ func (c *CoreHandler) applyChanges(snapshotApi model.Snapshot, account model.Acc
202187
}
203188
} else if len(diff.Changes) > 0 {
204189
changeSource = "API"
205-
account = c.applyChangesToAPI(account, repositoryData, diff)
190+
account, err = c.pushChangesToAPI(account, repositoryData, diff)
206191
}
207192

208193
return changeSource, account, err
209194
}
210195

211-
func (c *CoreHandler) applyChangesToAPI(account model.Account, repositoryData *model.RepositoryData, diff model.DiffResult) model.Account {
212-
utils.LogInfo("[%s - %s (%s)] Pushing changes to API", account.ID.Hex(), account.Domain.Name, account.Environment)
196+
func (c *CoreHandler) pushChangesToAPI(account model.Account,
197+
repositoryData *model.RepositoryData, diff model.DiffResult) (model.Account, error) {
198+
utils.LogInfo("[%s - %s (%s)] Pushing changes to API (prune: %t)", account.ID.Hex(), account.Domain.Name,
199+
account.Environment, account.Settings.ForcePrune)
213200

214201
// Removed deleted if force prune is disabled
215202
if !account.Settings.ForcePrune {
216-
c.comparatorService.RemoveDeleted(diff)
203+
diff = c.comparatorService.RemoveDeleted(diff)
217204
}
218205

219206
// Push changes to API
207+
apiResponse, err := c.apiService.PushChanges(account.Domain.ID, account.Environment, diff)
208+
209+
if err != nil {
210+
return account, err
211+
}
220212

221213
// Update domain
222-
account.Domain.Version = 2
214+
account.Domain.Version = apiResponse.Version
223215
account.Domain.LastCommit = repositoryData.CommitHash
224216

225-
return account
217+
return account, nil
226218
}
227219

228-
func (c *CoreHandler) applyChangesToRepository(account model.Account, snapshot model.Snapshot, gitService IGitService) (model.Account, error) {
220+
func (c *CoreHandler) pushChangesToRepository(account model.Account, snapshot model.Snapshot,
221+
gitService IGitService) (model.Account, error) {
229222
utils.LogInfo("[%s - %s (%s)] Pushing changes to repository", account.ID.Hex(), account.Domain.Name, account.Environment)
230223

231224
// Remove version from domain
232225
snapshotContent := snapshot
233226
snapshotContent.Domain.Version = 0
234227

228+
// Push changes to repository
235229
lastCommit, err := gitService.PushChanges(account.Environment, utils.ToJsonFromObject(snapshotContent))
236230

237231
if err != nil {
@@ -248,8 +242,9 @@ func (c *CoreHandler) applyChangesToRepository(account model.Account, snapshot m
248242
func (c *CoreHandler) isOutSync(account model.Account, lastCommit string, snapshotVersionPayload string) bool {
249243
snapshotVersion := c.apiService.NewDataFromJson([]byte(snapshotVersionPayload)).Snapshot.Domain.Version
250244

251-
utils.LogDebug("[%s - %s (%s)] Checking account - Last commit: %s - Domain Version: %d - Snapshot Version: %d",
252-
account.ID.Hex(), account.Domain.Name, account.Environment, account.Domain.LastCommit, account.Domain.Version, snapshotVersion)
245+
utils.LogDebug("[%s - %s (%s)] Checking account - Last commit: %s - GitOps Version: %d - API Version: %d",
246+
account.ID.Hex(), account.Domain.Name, account.Environment, account.Domain.LastCommit,
247+
account.Domain.Version, snapshotVersion)
253248

254249
return account.Domain.LastCommit == "" || // First sync
255250
account.Domain.LastCommit != lastCommit || // Repository out of sync
@@ -261,7 +256,9 @@ func (c *CoreHandler) isRepositoryOutSync(repositoryData *model.RepositoryData,
261256
len(diff.Changes) > 0 // Changes detected
262257
}
263258

264-
func (c *CoreHandler) updateDomainStatus(account model.Account, status string, message string) {
259+
func (c *CoreHandler) updateDomainStatus(account model.Account, status string, message string, logLevel string) {
260+
utils.Log(logLevel, "[%s - %s (%s)] %s", account.ID.Hex(), account.Domain.Name, account.Environment, message)
261+
265262
account.Domain.Status = status
266263
account.Domain.Message = message
267264
account.Domain.LastDate = time.Now().Format(time.ANSIC)

0 commit comments

Comments
 (0)