Skip to content

Commit

Permalink
chore: optimize runs api
Browse files Browse the repository at this point in the history
  • Loading branch information
ffforest committed Nov 14, 2024
1 parent b29fc4e commit aa7ef26
Show file tree
Hide file tree
Showing 14 changed files with 166 additions and 51 deletions.
5 changes: 5 additions & 0 deletions pkg/domain/constant/global.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,9 @@ const (
RepoCacheTTL = 60 * time.Minute
RunTimeOut = 60 * time.Minute
DefaultWorkloadSig = "kusion.io/is-workload"
ResourcePageDefault = 1
ResourcePageSizeDefault = 100
ResourcePageSizeLarge = 1000
RunPageDefault = 1
RunPageSizeDefault = 10
)
1 change: 1 addition & 0 deletions pkg/domain/constant/organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ var (
ErrBackendNil = errors.New("backend is nil")
ErrBackendNameEmpty = errors.New("backend must have a name")
ErrBackendTypeEmpty = errors.New("backend must have a type")
ErrDefaultBackendNotSet = errors.New("default backend not set properly")
ErrAppConfigHasNilStack = errors.New("appConfig has nil stack")
ErrInvalidOrganizationName = errors.New("organization name can only have alphanumeric characters and underscores with [a-zA-Z0-9_]")
ErrInvalidOrganizationID = errors.New("the organization ID should be a uuid")
Expand Down
15 changes: 11 additions & 4 deletions pkg/domain/entity/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ type Run struct {
Status constant.RunStatus `yaml:"status" json:"status"`
// Result is the result of the run.
Result string `yaml:"result" json:"result"`
// Result RunResult `yaml:"result" json:"result"`
// Trace is the trace of the run.
Trace string `yaml:"trace" json:"trace"`
// Logs is the logs of the run.
Logs string `yaml:"logs" json:"logs"`
// CreationTimestamp is the timestamp of the created for the run.
Expand All @@ -44,9 +45,15 @@ type RunResult struct {
}

type RunFilter struct {
ProjectID uint
StackID uint
Workspace string
ProjectID uint
StackID uint
Workspace string
Pagination *Pagination
}

type RunListResult struct {
Runs []*Run
Total int
}

// Validate checks if the run is valid.
Expand Down
6 changes: 6 additions & 0 deletions pkg/domain/entity/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package entity

type Pagination struct {
Page int `json:"page"`
PageSize int `json:"pageSize"`
}
2 changes: 1 addition & 1 deletion pkg/domain/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,5 @@ type RunRepository interface {
// Get retrieves a run by its ID.
Get(ctx context.Context, id uint) (*entity.Run, error)
// List retrieves all existing run.
List(ctx context.Context, filter *entity.RunFilter) ([]*entity.Run, error)
List(ctx context.Context, filter *entity.RunFilter) (*entity.RunListResult, error)
}
12 changes: 12 additions & 0 deletions pkg/domain/response/resource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package response

import (
"kusionstack.io/kusion/pkg/domain/entity"
)

type PaginatedResourceResponse struct {
Resources []*entity.Resource `json:"resources"`
Total int `json:"total"`
CurrentPage int `json:"currentPage"`
PageSize int `json:"pageSize"`
}
12 changes: 12 additions & 0 deletions pkg/domain/response/run.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package response

import (
"kusionstack.io/kusion/pkg/domain/entity"
)

type PaginatedRunResponse struct {
Runs []*entity.Run `json:"runs"`
Total int `json:"total"`
CurrentPage int `json:"currentPage"`
PageSize int `json:"pageSize"`
}
20 changes: 15 additions & 5 deletions pkg/infra/persistence/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,24 @@ func (r *runRepository) Get(ctx context.Context, id uint) (*entity.Run, error) {
}

// List retrieves all runs.
func (r *runRepository) List(ctx context.Context, filter *entity.RunFilter) ([]*entity.Run, error) {
func (r *runRepository) List(ctx context.Context, filter *entity.RunFilter) (*entity.RunListResult, error) {
var dataModel []RunModel
runEntityList := make([]*entity.Run, 0)
pattern, args := GetRunQuery(filter)
result := r.db.WithContext(ctx).
searchResult := r.db.WithContext(ctx).
Preload("Stack").Preload("Stack.Project").
Joins("JOIN stack ON stack.id = run.stack_id").
Joins("JOIN project ON project.id = stack.project_id").
Joins("JOIN workspace ON workspace.name = run.workspace").
Where(pattern, args...).
Find(&dataModel)
Where(pattern, args...)

// Get total rows
var totalRows int64
searchResult.Model(dataModel).Count(&totalRows)

// Fetch paginated data from searchResult with offset and limit
offset := (filter.Pagination.Page - 1) * filter.Pagination.PageSize
result := searchResult.Offset(offset).Limit(filter.Pagination.PageSize).Find(&dataModel)
if result.Error != nil {
return nil, result.Error
}
Expand All @@ -117,5 +124,8 @@ func (r *runRepository) List(ctx context.Context, filter *entity.RunFilter) ([]*
}
runEntityList = append(runEntityList, runEntity)
}
return runEntityList, nil
return &entity.RunListResult{
Runs: runEntityList,
Total: int(totalRows),
}, nil
}
17 changes: 10 additions & 7 deletions pkg/infra/persistence/run_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ type RunModel struct {
Result string
// Logs is the logs of the run.
Logs string
// Trace is the trace of the run.
Trace string
}

// The TableName method returns the name of the database table that the struct is mapped to.
Expand Down Expand Up @@ -53,13 +55,13 @@ func (m *RunModel) ToEntity() (*entity.Run, error) {
}

return &entity.Run{
ID: m.ID,
Type: runType,
Stack: stackEntity,
Workspace: m.Workspace,
Status: runStatus,
Result: m.Result,
// Result: entity.RunResult{},
ID: m.ID,
Type: runType,
Stack: stackEntity,
Workspace: m.Workspace,
Status: runStatus,
Result: m.Result,
Trace: m.Trace,
Logs: m.Logs,
CreationTimestamp: m.CreatedAt,
UpdateTimestamp: m.UpdatedAt,
Expand All @@ -83,6 +85,7 @@ func (m *RunModel) FromEntity(e *entity.Run) error {
m.Status = string(e.Status)
m.Result = e.Result
m.Logs = e.Logs
m.Trace = e.Trace
m.CreatedAt = e.CreationTimestamp
m.UpdatedAt = e.UpdateTimestamp

Expand Down
8 changes: 1 addition & 7 deletions pkg/server/handler/stack/execute_async.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,12 @@ func (h *Handler) PreviewStackAsync() http.HandlerFunc {
// Call preview stack
changes, err := h.stackManager.PreviewStack(newCtx, params, requestPayload.ImportedResources)
if err != nil {
// render.Render(w, r, handler.FailureResponse(ctx, err))
logger.Error("Error previewing stack", "error", err)
return
}

previewChanges, err = stackmanager.ProcessChanges(newCtx, w, changes, params.Format, params.ExecuteParams.Detail)
if err != nil {
// render.Render(w, r, handler.FailureResponse(ctx, err))
logger.Error("Error processing preview changes", "error", err)
return
}
Expand Down Expand Up @@ -206,7 +204,6 @@ func (h *Handler) ApplyStackAsync() http.HandlerFunc {
render.Render(w, r, handler.SuccessResponse(ctx, "Dry-run mode enabled, the above resources will be applied if dryrun is set to false"))
return
} else {
// render.Render(w, r, handler.FailureResponse(ctx, err))
logger.Error("Error applying stack", "error", err)
return
}
Expand Down Expand Up @@ -308,9 +305,8 @@ func (h *Handler) GenerateStackAsync() http.HandlerFunc {
}()

// Call generate stack
_, sp, err := h.stackManager.GenerateSpec(newCtx, params)
_, sp, err = h.stackManager.GenerateSpec(newCtx, params)
if err != nil {
// render.Render(w, r, handler.FailureResponse(ctx, err))
logger.Error("Error generating stack", "error", err)
return
}
Expand Down Expand Up @@ -400,11 +396,9 @@ func (h *Handler) DestroyStackAsync() http.HandlerFunc {
err = h.stackManager.DestroyStack(newCtx, params, w)
if err != nil {
if err == stackmanager.ErrDryrunDestroy {
// render.Render(w, r, handler.SuccessResponse(ctx, "Dry-run mode enabled, the above resources will be destroyed if dryrun is set to false"))
logger.Info("Dry-run mode enabled, the above resources will be destroyed if dryrun is set to false")
return
} else {
// render.Render(w, r, handler.FailureResponse(ctx, err))
logger.Error("Error destroying stack", "error", err)
return
}
Expand Down
21 changes: 15 additions & 6 deletions pkg/server/handler/stack/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"

"github.com/go-chi/render"
response "kusionstack.io/kusion/pkg/domain/response"
"kusionstack.io/kusion/pkg/server/handler"
logutil "kusionstack.io/kusion/pkg/server/util/logging"
)
Expand Down Expand Up @@ -95,18 +96,26 @@ func (h *Handler) ListRuns() http.HandlerFunc {
logger := logutil.GetLogger(ctx)
logger.Info("Listing runs...")

projectIDParam := r.URL.Query().Get("projectID")
stackIDParam := r.URL.Query().Get("stackID")
workspaceParam := r.URL.Query().Get("workspace")

filter, err := h.stackManager.BuildRunFilter(ctx, projectIDParam, stackIDParam, workspaceParam)
query := r.URL.Query()
filter, err := h.stackManager.BuildRunFilter(ctx, &query)
if err != nil {
render.Render(w, r, handler.FailureResponse(ctx, err))
return
}

// List runs
runEntities, err := h.stackManager.ListRuns(ctx, filter)
handler.HandleResult(w, r, ctx, err, runEntities)
if err != nil {
render.Render(w, r, handler.FailureResponse(ctx, err))
return
}
paginatedResponse := response.PaginatedRunResponse{
Runs: runEntities.Runs,
Total: runEntities.Total,
CurrentPage: filter.Pagination.Page,
PageSize: filter.Pagination.PageSize,
}
handler.HandleResult(w, r, ctx, err, paginatedResponse)
}
}

Expand Down
Loading

0 comments on commit aa7ef26

Please sign in to comment.