Skip to content

Commit

Permalink
[olivercodes] feat(gh-2): updated service tests, readme, pkg structur…
Browse files Browse the repository at this point in the history
…e, readiness and liveness probes
  • Loading branch information
olivercodes committed Jun 27, 2023
1 parent aa82eaa commit 92e1dfe
Show file tree
Hide file tree
Showing 13 changed files with 277 additions and 83 deletions.
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# lab-api-teams

### Local Execution

TODO: automate/script local setup

```
$ go get
$ docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:latest
$ go run cmd/teams-api-server/main.go
```

### Project structure
``` bash
.
├── README.md
Expand All @@ -17,11 +28,12 @@
│   │   └── handler.go
│   ├── repository
│   │   ├── mock
│   │   │   ├── mock_repository.go
│   │   │   └── teams_api_repository_test.go
│   │   │   ├── mock_team_repository.go
│   │   │   └── mock_team_repository_test.go
│   │   └── redis_teams_api_repository.go
│   └── service
│   └── service.go
│   ├── service.go
│   └── service_test.go
└── scripts
└── curl.sh
```
2 changes: 2 additions & 0 deletions cmd/teams-api-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ func main() {
teamService := service.NewTeamService(teamRepo)
teamHandler := handler.NewTeamHandler(teamService)

router.GET("/teams/healthz/readiness", teamHandler.Readiness)
router.GET("/teams/healthz/liveness", teamHandler.Liveness)
router.GET("/teams/:teamID", teamHandler.GetTeam)
router.GET("/teams", teamHandler.GetTeams)
router.POST("/teams", teamHandler.AddTeam)
Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
Expand All @@ -25,6 +26,8 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.8.4 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
Expand Down Expand Up @@ -45,6 +46,7 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
Expand All @@ -56,6 +58,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
Expand Down
1 change: 1 addition & 0 deletions pkg/domain/teams.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,5 @@ type TeamRepository interface {
AddTeam(newTeam Team) error
UpdateTeam(team Team) error
RemoveTeam(id string) error
DatabaseAvailable() (bool, error)
}
21 changes: 21 additions & 0 deletions pkg/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,27 @@ func NewTeamHandler(teamService service.TeamService) *TeamHandler {
return &TeamHandler{teamService: teamService}
}

func (handler *TeamHandler) Liveness(c *gin.Context) {
c.Status(http.StatusOK)
c.IndentedJSON(http.StatusOK, gin.H{"message": "Teams api is live"})
}

// TODO - given that we implement many different database types, the database available function
// should return a string or object wsith the type in it, like { type: redis, conn_url: localhost:6379, available: true }
// This is good info for error logs when debugging (Database %s is not available yet, db.Type)
func (handler *TeamHandler) Readiness(c *gin.Context) {
dbReady, err := handler.teamService.DatabaseAvailable()
if err != nil {
c.IndentedJSON(http.StatusInternalServerError, err)
}

if dbReady != true {
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Database is not available"})
}

c.IndentedJSON(http.StatusOK, gin.H{"message": "DB is available"})
}

func (handler *TeamHandler) GetTeams(c *gin.Context) {
teams, err := handler.teamService.GetTeams()
if err != nil {
Expand Down
30 changes: 0 additions & 30 deletions pkg/repository/mock/mock_repository.go

This file was deleted.

65 changes: 65 additions & 0 deletions pkg/repository/mock/mock_team_repository.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package mock

import (
"fmt"

"twdps.io/lab-api-teams/pkg/domain"
)

type MockRepository struct {
Teams []domain.Team
}

func (m *MockRepository) GetTeams() ([]domain.Team, error) {
return m.Teams, nil
}

func (m *MockRepository) AddTeam(newTeam domain.Team) error {
m.Teams = append(m.Teams, newTeam)
return nil
}

func (m *MockRepository) GetTeam(id string) (domain.Team, error) {
for _, team := range m.Teams {
if id == team.TeamID {
return team, nil
}
}

return domain.Team{}, fmt.Errorf("Team not found")
}

func update_slice_item(slice []domain.Team, index int, team domain.Team) []domain.Team {
// Remove the index first
teams := append(slice[:index], slice[index+1:]...)
// Update with the new one
return append(teams, team)
}

func delete_slice_item(slice []domain.Team, index int) []domain.Team {
return append(slice[:index], slice[index+1:]...)
}

func (m *MockRepository) RemoveTeam(teamID string) error {
for index, team := range m.Teams {
if team.TeamID == teamID {
m.Teams = delete_slice_item(m.Teams, index)
}
}

return nil
}

func (m *MockRepository) UpdateTeam(teamToUpdate domain.Team) error {
for index, team := range m.Teams {
if team.TeamID == teamToUpdate.TeamID {
m.Teams = update_slice_item(m.Teams, index, teamToUpdate)
}
}

return nil
}

func (m *MockRepository) DatabaseAvailable() (bool, error) {
return true, nil
}
26 changes: 26 additions & 0 deletions pkg/repository/mock/mock_team_repository_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package mock

import (
"testing"

"twdps.io/lab-api-teams/pkg/domain"
"twdps.io/lab-api-teams/pkg/service"
)

func TestMock(t *testing.T) {
mockRepository := &MockRepository{
Teams: []domain.Team{
{TeamID: "team-sapphire", TeamType: "normal", TeamDescription: "Sapphire frontend team", TeamRAM: 32, TeamCPU: 12, TeamRamLimit: 64, TeamCpuLimit: 24},
},
}

// If Mock Repo didn't implement expected functions this will throw an InvalidIFaceAssign error
// - This is itself a test, albeit it is basically a compiler error test
teamService := service.NewTeamService(mockRepository)

// Sanity check that mock implements actual functionality. Rest of service tests are in service_test.go
teams, _ := teamService.GetTeams()
if len(teams) != 1 {
t.Errorf("expected %d teams got %d", 1, len(teams))
}
}
46 changes: 0 additions & 46 deletions pkg/repository/mock/teams_api_repository_test.go

This file was deleted.

18 changes: 14 additions & 4 deletions pkg/repository/redis_teams_api_repository.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package repository

// TODO - redis repository tests

import (
"context"
"encoding/json"
Expand Down Expand Up @@ -79,16 +81,12 @@ func (store *RedisTeamRepository) AddTeam(newTeam domain.Team) error {
}

func (store *RedisTeamRepository) UpdateTeam(team domain.Team) error {
// Construct the key for the team
teamKey := fmt.Sprintf("team:%s", team.TeamID)

// Marshal the updated team into JSON
updatedTeamJSON, err := json.Marshal(team)
if err != nil {
return fmt.Errorf("could not marshal team: %v", err)
}

// Store the updated team back in Redis
err = store.client.Set(store.ctx, teamKey, updatedTeamJSON, 0).Err()
if err != nil {
return fmt.Errorf("could not update team: %v", err)
Expand All @@ -111,3 +109,15 @@ func (store *RedisTeamRepository) RemoveTeam(teamID string) error {
return nil

}

func (store *RedisTeamRepository) DatabaseAvailable() (bool, error) {
res, err := store.client.Ping(store.ctx).Result()
if err != nil {
return false, fmt.Errorf("Redis was not reachable: %v", err)
}
if res != "PONG" {
return false, fmt.Errorf("Unexpected response from redis PING: %s", res)
}

return true, nil
}
14 changes: 14 additions & 0 deletions pkg/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type TeamService interface {
AddTeam(team domain.Team) error
RequestRemoveTeam(teamID string) error
ConfirmRemoveTeam(teamID string) error
DatabaseAvailable() (bool, error)
}

type teamServiceImpl struct {
Expand All @@ -24,6 +25,19 @@ func NewTeamService(repo domain.TeamRepository) TeamService {
}
}

func (s *teamServiceImpl) DatabaseAvailable() (bool, error) {
dbAvailable, err := s.repo.DatabaseAvailable()
if err != nil {
return false, err
}

if dbAvailable == false {
return false, fmt.Errorf("DB is not available yet")
}

return true, nil
}

func (s *teamServiceImpl) GetTeams() ([]domain.Team, error) {
teams, err := s.repo.GetTeams()
if err != nil {
Expand Down
Loading

0 comments on commit 92e1dfe

Please sign in to comment.