Skip to content

Commit

Permalink
feat: create snapshots
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored Jul 29, 2024
1 parent 60205fd commit 2bb25e1
Show file tree
Hide file tree
Showing 12 changed files with 532 additions and 57 deletions.
93 changes: 80 additions & 13 deletions api/api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,62 @@ paths:
- in: path
name: environmentName

/teams/{teamName}/projects/{projectName}/environments/{environmentName}/states:
get:
tags:
- States
summary: Get the state of Terraform environment
operationId: getStates
parameters:
- $ref: "#/components/parameters/teamName"
- $ref: "#/components/parameters/projectName"
- $ref: "#/components/parameters/environmentName"
- $ref: "#/components/parameters/limit"
- $ref: "#/components/parameters/offset"
security:
- openId: []
responses:
"200":
description: Successful response
content:
application/json:
schema:
type: object
properties:
states:
type: array
items:
$ref: "#/components/schemas/State"
"404":
description: Resource not found
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
"500":
description: Internal Server Error
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
# Add the policy to check if the user has access to delete the project
x-fiber-authz-fga:
user:
namespace: user
auth_type: oidc
relation:
name: reader
object:
namespace: environment
separator: /
components:
- in: path
name: teamName
- in: path
name: projectName
- in: path
name: environmentName

/teams/{teamName}/projects/{projectName}/environments/{environmentName}/snapshots:
get:
tags:
Expand Down Expand Up @@ -1180,25 +1236,17 @@ components:
type: string
description:
type: string
record_type:
type: string
record_uuid:
type: string
status:
type: string
team:
type: object
properties:
id:
type: string
name:
type: string
version:
type: integer
createdAt:
type: string
format: date-time
updatedAt:
type: string
format: date-time
deletedAt:
type: string
format: date-time

SnapshotCreate:
type: object
Expand Down Expand Up @@ -1231,6 +1279,25 @@ components:
type: object
format: binary

State:
type: object
properties:
id:
type: string
state:
type: string
version:
type: integer
createdAt:
type: string
format: date-time
updatedAt:
type: string
format: date-time
deletedAt:
type: string
format: date-time

securitySchemes:
openId:
type: http
Expand Down
10 changes: 7 additions & 3 deletions internal/adapters/database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package database
import (
"context"
"errors"
"fmt"

"github.com/zeiss/fiber-htmx/components/tables"
"github.com/zeiss/knox/internal/models"
Expand Down Expand Up @@ -91,6 +90,13 @@ func (r *readTxImpl) AuthenticateClient(ctx context.Context, teamId, projectId,
return environment.ComparePassword(password)
}

// ListStates ...
func (r *readTxImpl) ListStates(ctx context.Context, teamName, projectName, environmentName string, results *tables.Results[models.State]) error {
return r.conn.Scopes(tables.PaginatedResults(&results.Rows, results, r.conn)).
Where("environment_id = (?)", r.conn.Model(&models.Environment{}).Where("name = ?", environmentName).Where("project_id = (?)", r.conn.Model(&models.Project{}).Where("name = ?", projectName).Where("owner_id = (?)", r.conn.Model(&models.Team{}).Where("name = ?", teamName).Select("id")).Select("id")).Select("id")).
Find(&results.Rows).Error
}

type writeTxImpl struct {
conn *gorm.DB
readTxImpl
Expand Down Expand Up @@ -130,8 +136,6 @@ func (rw *writeTxImpl) DeleteProject(ctx context.Context, teamName string, proje
func (rw *writeTxImpl) UpdateState(ctx context.Context, teamName string, projectName string, state *models.State) error {
latest := models.State{}

fmt.Println("teamName: ", teamName, "projectName: ", projectName)

result := rw.conn.Debug().
Where(&models.State{}).
Where("project_id = (?)", rw.conn.Model(&models.Project{}).Where("name = ?", projectName).Where("owner_id = (?)", rw.conn.Model(&models.Team{}).Where("name = ?", teamName).Select("id")).Select("id")).
Expand Down
15 changes: 15 additions & 0 deletions internal/adapters/handlers/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ func (h *apiHandlers) GetSnapshot(ctx context.Context, request openapi.GetSnapsh
return nil, fiber.NewError(fiber.StatusNotImplemented, "not implemented")
}

// Update a snapshot

// Get a list of teams
// (GET /team)
func (h *apiHandlers) GetTeams(ctx context.Context, request openapi.GetTeamsRequestObject) (openapi.GetTeamsResponseObject, error) {
Expand Down Expand Up @@ -299,3 +301,16 @@ func (a *apiHandlers) UnlockEnvironment(ctx context.Context, request openapi.Unl

return dto.ToUnlockEnvironmentResponseObject(), nil
}

// Get the state of Terraform environment
// (GET /teams/{teamName}/projects/{projectName}/environments/{environmentName}/states)
func (a *apiHandlers) GetStates(ctx context.Context, request openapi.GetStatesRequestObject) (openapi.GetStatesResponseObject, error) {
query := dto.FromGetStatesRequestObject(request)

results, err := a.environment.ListStates(ctx, query)
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}

return dto.ToGetStatesResponseObject(results), nil
}
27 changes: 27 additions & 0 deletions internal/controllers/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ type DeleteEnvironmentCommand struct {
EnvironmentName string `json:"environment_name" form:"environment_name" validate:"required"`
}

// ListStatesQuery ...
type ListStatesQuery struct {
TeamName string `json:"team_name" form:"team_name" validate:"required"`
ProjectName string `json:"project_name" form:"project_name" validate:"required"`
EnvironmentName string `json:"environment_name" form:"environment_name" validate:"required"`
Limit int `json:"limit" form:"limit" validate:"omitempty,min=1,max=100"`
Offset int `json:"offset" form:"offset" validate:"omitempty,min=0"`
}

// EnvironmentControllerImpl ...
type EnvironmentControllerImpl struct {
store seed.Database[ports.ReadTx, ports.ReadWriteTx]
Expand All @@ -61,6 +70,8 @@ type EnvironmentController interface {
GetEnvironment(ctx context.Context, query GetEnvironmentQuery) (models.Environment, error)
// DeleteEnvironment ...
DeleteEnvironment(ctx context.Context, cmd DeleteEnvironmentCommand) error
// ListStates ...
ListStates(ctx context.Context, query ListStatesQuery) (tables.Results[models.State], error)
}

// NewEnvironmentController ...
Expand Down Expand Up @@ -164,3 +175,19 @@ func (c *EnvironmentControllerImpl) DeleteEnvironment(ctx context.Context, cmd D
return tx.DeleteEnvironment(ctx, cmd.TeamName, cmd.ProjectName, &environment)
})
}

// ListStates ...
func (c *EnvironmentControllerImpl) ListStates(ctx context.Context, query ListStatesQuery) (tables.Results[models.State], error) {
validate = validator.New()

results := tables.Results[models.State]{}

err := c.store.ReadTx(ctx, func(ctx context.Context, tx ports.ReadTx) error {
return tx.ListStates(ctx, query.TeamName, query.ProjectName, query.EnvironmentName, &results)
})
if err != nil {
return results, err
}

return results, nil
}
4 changes: 3 additions & 1 deletion internal/controllers/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
seed "github.com/zeiss/gorm-seed"
"github.com/zeiss/knox/internal/models"
"github.com/zeiss/knox/internal/ports"
"github.com/zeiss/knox/pkg/utils"

"github.com/google/uuid"
)
Expand Down Expand Up @@ -50,9 +51,10 @@ func (c *SnapshotControllerImpl) CreateSnapshot(ctx context.Context, cmd CreateS

snapshot := models.Snapshot{
Title: cmd.Title,
Description: &cmd.Description,
Description: utils.StrPtr(cmd.Description),
EnvironmentID: state.EnvironmentID,
ProjectID: state.ProjectID,
StateID: state.ID,
Data: state.Data,
}

Expand Down
10 changes: 6 additions & 4 deletions internal/models/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ type Snapshot struct {
// Environment is the environment of the state.
Environment Environment `json:"environment" form:"environment"`
// EnvironmentID is the environment id of the state.
EnvironmentID uuid.UUID `json:"environment_id" gorm:"uniqueIndex:idx_project_environment_version"`
EnvironmentID uuid.UUID `json:"environment_id" gorm:"uniqueIndex:idx_project_environment_state"`
// Project is the project of the state.
Project Project `json:"project" form:"project"`
// ProjectID is the project id of the state.
ProjectID uuid.UUID `json:"project_id" gorm:"uniqueIndex:idx_project_environment_version"`
// Version is the version of the state.
Version int `json:"version" gorm:"uniqueIndex:idx_project_environment_version"`
ProjectID uuid.UUID `json:"project_id" gorm:"uniqueIndex:idx_project_environment_state"`
// State is the state of the snapshot.
State State `json:"state" form:"state"`
// StateID is the state id of the snapshot.
StateID uuid.UUID `json:"version" gorm:"uniqueIndex:idx_project_environment_state"`
// Data is the data of the state.
Data datatypes.JSON `json:"data" form:"data"`
// CreatedAt is the time the snapshot was created.
Expand Down
2 changes: 2 additions & 0 deletions internal/ports/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ type ReadTx interface {
ListEnvironments(context.Context, string, string, *tables.Results[models.Environment]) error
// ListTeams ...
ListTeams(context.Context, *tables.Results[models.Team]) error
// ListStates ...
ListStates(context.Context, string, string, string, *tables.Results[models.State]) error
}

// ReadWriteTx provides methods for transactional read and write operations.
Expand Down
Loading

0 comments on commit 2bb25e1

Please sign in to comment.