usecase

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 31, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrReleaseNotFound 는 클러스터에 그 릴리스가 없을 때다.
	ErrReleaseNotFound = errors.New("release not found")
	// ErrReleaseValuesInvalidYAML 은 편집본이 YAML 매핑으로 읽히지 않을 때다.
	ErrReleaseValuesInvalidYAML = errors.New("invalid yaml values")
	// ErrReleaseValuesInvalidMode 는 모드 값이 live/override 가 아닐 때다.
	ErrReleaseValuesInvalidMode = errors.New("invalid release values mode")
)
View Source
var ErrDeploymentCancelled = errors.New("deployment canceled")
View Source
var ErrImportConfirmationRequired = errors.New("import confirmation required")
View Source
var ErrStackNotFound = errors.New("stack not found")

Functions

func BuildStackTokenSourceInputs

func BuildStackTokenSourceInputs(
	stack *domain.Stack,
	env string,
	creds SourceControlCredentials,
) []port.TokenSourceInput

BuildStackTokenSourceInputs 는 스택 설치가 끝난 뒤 등록할 토큰 소스를 만든다.

두 종류가 조건이 다르다. 회전 대상 항목은 사용자가 인증 공급자로 OpenBao 를 고른 스택에만 만들고, 사용자가 직접 준 GitHub PAT 는 그 선택과 무관하게 만든다. 자세한 이유는 각 분기의 주석에 있다.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError reports whether err wraps (or is) a CompatibilityValidationError.

func TopLevelValuePaths

func TopLevelValuePaths(yamlText string) []string

TopLevelValuePaths 는 편집본이 건드린 최상위 키를 정렬해 돌려준다.

감사 로그에 "무엇을 바꿨나" 를 남기되 값은 남기지 않기 위한 것이다. values 에는 사용자가 직접 적어 넣은 자격증명이 들어갈 수 있고, 감사 로그는 그보다 넓게 읽힌다. 값 자체는 스택 설정 이력(stack_config_versions)에 남으므로 되짚을 수 있다.

파싱되지 않는 편집본이면 빈 슬라이스다 — 감사 기록이 파싱 실패로 통째로 사라지면 안 되므로 여기서 에러를 올리지 않는다.

func VerdictCacheKey

func VerdictCacheKey(input ValidateCompatibilityInput) string

VerdictCacheKey derives a stable key for a validate input. Any field that influences the verdict is folded into a sha256 so matrix drift / tool edits / cluster arch changes each produce a new key.

Types

type AddToolsInput

type AddToolsInput struct {
	StackID string
	Tools   []domain.ToolConfig
}

type AddToolsUseCase

type AddToolsUseCase struct {
	// contains filtered or unexported fields
}

func NewAddToolsUseCase

func NewAddToolsUseCase(repo port.StackRepository) *AddToolsUseCase

func (*AddToolsUseCase) Execute

func (uc *AddToolsUseCase) Execute(ctx context.Context, input AddToolsInput) (*domain.Stack, error)

type ApplyReleaseValuesInput

type ApplyReleaseValuesInput struct {
	StackID     string
	ReleaseName string
	Mode        ReleaseValuesMode
	YAML        string
	DryRun      bool
	ChangedBy   string
}

ApplyReleaseValuesInput 은 적용(또는 드라이런) 파라미터다.

type ApplyReleaseValuesOutput

type ApplyReleaseValuesOutput struct {
	ReleaseName string                           `json:"release_name"`
	StepName    string                           `json:"step_name,omitempty"`
	Namespace   string                           `json:"namespace"`
	Mode        ReleaseValuesMode                `json:"mode"`
	Revision    int                              `json:"revision"`
	Status      string                           `json:"status,omitempty"`
	DryRun      bool                             `json:"dry_run"`
	Warnings    []domain.ProtectedValueViolation `json:"warnings,omitempty"`
	// EffectiveYAML 은 실제로 helm 에 넘어간 values 다. 오버라이드 모드에서
	// 병합 결과를 확인하는 용도이므로 드라이런에서 특히 중요하다.
	EffectiveYAML string `json:"effective_yaml,omitempty"`
	Manifest      string `json:"manifest,omitempty"`
	// RenderError 는 미리보기에서만 채워진다. 차트가 렌더되지 않는 것은
	// 편집 결과이지 서버 오류가 아니므로, 경고와 함께 돌려준다.
	RenderError string `json:"render_error,omitempty"`
}

ApplyReleaseValuesOutput 은 적용 결과다.

type CalculateResources

type CalculateResources struct{}

CalculateResources computes estimated resource requirements for a tool set.

func NewCalculateResources

func NewCalculateResources() *CalculateResources

NewCalculateResources constructs a CalculateResources use case.

func (*CalculateResources) Execute

Execute computes the resource estimate.

type CompatibilityValidationError

type CompatibilityValidationError struct {
	Field   string
	Message string
}

CompatibilityValidationError is a 400-shaped error the handler layer maps to HTTP 400 without string matching.

func (*CompatibilityValidationError) Code

Code returns the string error code for JSON payloads.

func (*CompatibilityValidationError) Error

func (*CompatibilityValidationError) HTTPStatus

func (e *CompatibilityValidationError) HTTPStatus() int

HTTPStatus is the recommended mapping — handlers can type-assert and pull the right status code without hard-coding.

type CreateStack

type CreateStack struct {
	// contains filtered or unexported fields
}

CreateStack creates a new stack configuration, optionally loading defaults from a template.

func NewCreateStack

func NewCreateStack(stackRepo port.StackRepository, templateRepo port.TemplateRepository, opts ...CreateStackOption) *CreateStack

NewCreateStack constructs a CreateStack use case.

func (*CreateStack) Execute

func (uc *CreateStack) Execute(ctx context.Context, input CreateStackInput) (*CreateStackOutput, error)

Execute creates a new stack, merging template defaults when a TemplateID is provided.

type CreateStackInput

type CreateStackInput struct {
	Name       string
	OrgID      string
	ClusterID  string
	Namespace  string
	TemplateID string
	Config     domain.StackConfig
}

CreateStackInput holds the parameters for creating a new stack.

type CreateStackOption

type CreateStackOption func(*CreateStack)

CreateStackOption configures optional CreateStack dependencies.

func WithManageHistory

func WithManageHistory(manageHistory *ManageHistory) CreateStackOption

WithManageHistory enables automatic initial version snapshots.

func WithPlatformNamespace

func WithPlatformNamespace(namespace string) CreateStackOption

WithPlatformNamespace 는 플랫폼이 사는 네임스페이스를 알려준다.

그곳에 스택을 세우면 설치는 Helm 소유권 충돌로 실패하고(플랫폼의 nullus-postgresql 과 이름이 겹친다), 삭제는 플랫폼 리소스를 지운다 — 2026-08-20 에 실제로 nullus.io 가 통째로 내려갔다.

func WithResourcePlanning

func WithResourcePlanning(resourceDefaults port.ResourceDefaultRepository) CreateStackOption

WithResourcePlanning 은 템플릿의 planning_profile 로 설치 규모를 계획하게 한다.

계획 계산은 원래 설치 마법사에만 있었다. 그래서 API 로 만든 스택은 프로파일을 저장만 하고 크기에는 반영하지 않아, Lite 템플릿도 standard 크기로 깔렸다.

type CreateStackOutput

type CreateStackOutput struct {
	Stack *domain.Stack
}

CreateStackOutput holds the result of creating a stack.

type DeleteStack

type DeleteStack struct {
	// contains filtered or unexported fields
}

func NewDeleteStack

func NewDeleteStack(
	stackRepo port.StackRepository,
	kubeconfigProvider port.KubeconfigProvider,
	executorFactory func(kubeconfig []byte) port.HelmInstaller,
	streamer ...port.LogStreamer,
) *DeleteStack

func (*DeleteStack) Execute

func (uc *DeleteStack) Execute(ctx context.Context, stackID string) error

Execute 는 스택을 지우고 클러스터 정리가 끝날 때까지 기다린다.

func (*DeleteStack) ExecuteAsync

func (uc *DeleteStack) ExecuteAsync(ctx context.Context, stackID string) error

ExecuteAsync 는 레코드만 요청 안에서 지우고, 클러스터 정리는 요청에서 떼어 보낸다.

정리는 릴리스 uninstall 과 PVC 재시도만으로도 몇 분이 걸리는데 HTTP 요청은 그만큼 살아 있지 않다. 요청 컨텍스트에 매달아 두면 게이트웨이가 연결을 끊는 순간 정리가 중간에서 멈추고, 마지막 단계인 볼륨·네임스페이스 회수는 아예 실행되지 않는다 — 2026-08-21 운영에서 스택을 지운 뒤 PVC 와 네임스페이스가 함께 남았다.

레코드 삭제만 요청 안에서 끝내는 이유는, 목록 새로고침이 방금 지운 스택을 다시 보여주면 사용자가 삭제가 실패한 줄 알기 때문이다. 정리 진행 상황은 이벤트 스트림으로 계속 나간다.

func (*DeleteStack) SetPlatformNamespace

func (uc *DeleteStack) SetPlatformNamespace(namespace string)

SetPlatformNamespace 는 플랫폼 자신이 사는 네임스페이스를 알려준다.

스택이 그 네임스페이스에 깔려 있으면 이름 기반 청소를 하지 않는다. 소유권 판정만으로도 남의 것은 지키지만, 플랫폼을 지우는 사고는 한 번으로 족하다.

func (*DeleteStack) SetSSOProvisionerFactory

func (uc *DeleteStack) SetSSOProvisionerFactory(factory port.SSOProvisionerFactory)

SetSSOProvisionerFactory 는 SSO provisioner 생성기를 주입한다.

설치 때와 같은 팩토리여야 같은 client ID 를 계산해 지울 수 있다.

type DiffResult

type DiffResult struct {
	Added   map[string]any    `json:"added"`
	Removed map[string]any    `json:"removed"`
	Changed map[string][2]any `json:"changed"`
}

type DiffVersions

type DiffVersions struct {
	// contains filtered or unexported fields
}

func NewDiffVersions

func NewDiffVersions(historyRepo port.HistoryRepository) *DiffVersions

func (*DiffVersions) Execute

func (uc *DiffVersions) Execute(ctx context.Context, input DiffVersionsInput) (*DiffResult, error)

type DiffVersionsInput

type DiffVersionsInput struct {
	StackID  string
	VersionA int
	VersionB int
}

type EstimateResourcesInput

type EstimateResourcesInput struct {
	Tools    []ToolInstance
	Workload WorkloadInput
}

EstimateResourcesInput holds parameters for resource estimation.

type EstimateResourcesOutput

type EstimateResourcesOutput struct {
	Summary             domain.ResourceEstimate
	PerTool             []ToolResourceEstimate
	Notes               []string
	WorkloadScaleFactor float64
	ArtifactStorageGi   float64
	CostBreakdown       ResourceCostBreakdown
}

EstimateResourcesOutput holds the full resource estimation result.

type ExportConfig

type ExportConfig struct {
	// contains filtered or unexported fields
}

ExportConfig exports a stack's configuration as JSON or YAML.

func NewExportConfig

func NewExportConfig(stackRepo port.StackRepository) *ExportConfig

NewExportConfig constructs an ExportConfig use case.

func (*ExportConfig) BuildExport

func (uc *ExportConfig) BuildExport(ctx context.Context, stackID string) (*ExportedStack, error)

BuildExport returns the portable export payload for a stack.

func (*ExportConfig) ExportAsJSON

func (uc *ExportConfig) ExportAsJSON(ctx context.Context, stackID string) ([]byte, error)

ExportAsJSON returns the stack configuration serialized as indented JSON.

func (*ExportConfig) ExportAsYAML

func (uc *ExportConfig) ExportAsYAML(ctx context.Context, stackID string) ([]byte, error)

ExportAsYAML returns the stack configuration serialized as YAML.

type ExportSpec

type ExportSpec struct {
	SchemaVersion string                 `json:"schema_version" yaml:"schema_version"`
	Name          string                 `json:"name" yaml:"name"`
	TemplateID    string                 `json:"template_id" yaml:"template_id"`
	OrgID         string                 `json:"org_id" yaml:"org_id"`
	ClusterID     string                 `json:"cluster_id" yaml:"cluster_id"`
	Namespace     string                 `json:"namespace" yaml:"namespace"`
	State         domain.DeploymentState `json:"state,omitempty" yaml:"state,omitempty"`
	Tools         []domain.ToolConfig    `json:"tools,omitempty" yaml:"tools,omitempty"`
	Config        domain.StackConfig     `json:"config" yaml:"config"`
	Resources     domain.ResourcesConfig `json:"resources" yaml:"resources"`
}

ExportSpec holds the canonical exported stack specification.

type ExportedStack

type ExportedStack struct {
	Kind       string     `json:"kind" yaml:"kind"`
	APIVersion string     `json:"apiVersion" yaml:"apiVersion"`
	Spec       ExportSpec `json:"spec" yaml:"spec"`
}

ExportedStack is the portable representation used by export/import flows.

type GetConnectionInfo

type GetConnectionInfo struct {
	// contains filtered or unexported fields
}

GetConnectionInfo 는 스택 접속에 필요한 정보를 조립한다.

리소스 이름은 domain 의 상수에서 온다. 화면이 같은 값을 다시 조립하면 규칙이 갈리는 순간 조용히 어긋나므로, 서버가 확정된 값을 내려준다.

func NewGetConnectionInfo

func NewGetConnectionInfo(stacks connectionStackReader) *GetConnectionInfo

NewGetConnectionInfo 는 유스케이스를 만든다.

func (*GetConnectionInfo) Execute

func (uc *GetConnectionInfo) Execute(ctx context.Context, stackID string) (*domain.ConnectionInfo, error)

Execute 는 스택의 연결정보를 돌려준다.

type GetDiffInput

type GetDiffInput struct {
	StackID   string
	VersionID string
}

GetDiffInput holds parameters for computing a version diff.

type GetDiffOutput

type GetDiffOutput struct {
	Diffs []domain.ConfigDiff
}

GetDiffOutput holds the computed diff result.

type GetReleaseValuesInput

type GetReleaseValuesInput struct {
	StackID     string
	ReleaseName string
	Mode        ReleaseValuesMode
}

GetReleaseValuesInput 은 values 조회 파라미터다.

type GetTemplate

type GetTemplate struct {
	// contains filtered or unexported fields
}

GetTemplate retrieves a single Golden Path template by ID.

func NewGetTemplate

func NewGetTemplate(templateRepo port.TemplateRepository) *GetTemplate

NewGetTemplate constructs a GetTemplate use case.

func (*GetTemplate) Execute

func (uc *GetTemplate) Execute(ctx context.Context, input GetTemplateInput) (*GetTemplateOutput, error)

Execute retrieves a template by ID.

type GetTemplateInput

type GetTemplateInput struct {
	ID string
}

GetTemplateInput holds parameters for retrieving a single template.

type GetTemplateOutput

type GetTemplateOutput struct {
	Template *domain.Template
}

GetTemplateOutput holds the result of retrieving a template.

type ImportConfig

type ImportConfig struct {
	// contains filtered or unexported fields
}

ImportConfig restores a stack from an export payload.

func NewImportConfig

func NewImportConfig(createStack *CreateStack, addTools *AddToolsUseCase, installStack ...*InstallStack) *ImportConfig

func (*ImportConfig) Execute

func (*ImportConfig) Preview

type ImportConfigInput

type ImportConfigInput struct {
	OrgID           string
	Payload         []byte
	ReplaceExisting bool
}

ImportConfigInput holds the raw export payload and target org context.

type ImportConfigOutput

type ImportConfigOutput struct {
	Stack *domain.Stack
}

ImportConfigOutput returns the restored stack.

type ImportPreviewOutput

type ImportPreviewOutput struct {
	Mode            string      `json:"mode"`
	Name            string      `json:"name"`
	ClusterID       string      `json:"cluster_id"`
	ExistingStackID string      `json:"existing_stack_id,omitempty"`
	ExistingState   string      `json:"existing_state,omitempty"`
	Changes         *DiffResult `json:"changes,omitempty"`
}

type InstallStack

type InstallStack struct {
	// contains filtered or unexported fields
}

func NewInstallStack

func NewInstallStack(stackRepo port.StackRepository, streamer port.LogStreamer, opts ...InstallStackOption) *InstallStack

func (*InstallStack) Execute

func (uc *InstallStack) Execute(ctx context.Context, input InstallStackInput) error

Execute starts the installation in a goroutine and returns immediately. The caller can track progress by subscribing to the LogStreamer.

type InstallStackInput

type InstallStackInput struct {
	StackID        string
	Continue       bool
	PreserveLogs   bool
	ResumeFromStep string
	// SourceControl 은 외부 SCM 자격증명이다. 요청에서만 흐르고
	// stacks.config 에는 저장되지 않는다 — 설치가 끝나면 OpenBao 로 옮겨진다.
	SourceControl SourceControlCredentials
}

InstallStackInput holds the parameters for starting an installation.

type InstallStackOption

type InstallStackOption func(*InstallStack)

func WithExecutor

func WithExecutor(executor port.StepExecutor) InstallStackOption

func WithExecutorFactory

func WithExecutorFactory(factory func(kubeconfig []byte) port.StepExecutor) InstallStackOption

func WithKubeconfigProvider

func WithKubeconfigProvider(provider port.KubeconfigProvider) InstallStackOption

func WithSecretRouter

func WithSecretRouter(router *secrets.Router) InstallStackOption

func WithTokenSourceRegistry

func WithTokenSourceRegistry(registry port.TokenSourceRegistry, env string) InstallStackOption

type ListResourceDefaults

type ListResourceDefaults struct {
	// contains filtered or unexported fields
}

func (*ListResourceDefaults) Execute

type ListResourceDefaultsOutput

type ListResourceDefaultsOutput struct {
	Items []*domain.ResourceDefault
}

type ListStacks

type ListStacks struct {
	// contains filtered or unexported fields
}

ListStacks retrieves all stacks belonging to an organization.

func NewListStacks

func NewListStacks(stackRepo port.StackRepository) *ListStacks

NewListStacks constructs a ListStacks use case.

func (*ListStacks) Execute

func (uc *ListStacks) Execute(ctx context.Context, input ListStacksInput) (*ListStacksOutput, error)

Execute lists stacks for the given organization.

type ListStacksInput

type ListStacksInput struct {
	OrgID          string
	IncludeDeleted bool
}

ListStacksInput holds parameters for listing stacks.

type ListStacksOutput

type ListStacksOutput struct {
	Stacks []*domain.Stack
}

ListStacksOutput holds the result of listing stacks.

type ListTemplates

type ListTemplates struct {
	// contains filtered or unexported fields
}

ListTemplates retrieves all available Golden Path templates.

func NewListTemplates

func NewListTemplates(templateRepo port.TemplateRepository) *ListTemplates

NewListTemplates constructs a ListTemplates use case.

func (*ListTemplates) Execute

func (uc *ListTemplates) Execute(ctx context.Context) (*ListTemplatesOutput, error)

Execute lists all templates.

type ListTemplatesOutput

type ListTemplatesOutput struct {
	Templates []*domain.Template
}

ListTemplatesOutput holds the result of listing templates.

type ListVersionsInput

type ListVersionsInput struct {
	StackID string
}

ListVersionsInput holds parameters for listing stack versions.

type ListVersionsOutput

type ListVersionsOutput struct {
	Versions []*domain.StackVersion
}

ListVersionsOutput holds the result of listing stack versions.

type ManageCompatibility

type ManageCompatibility struct {
	// contains filtered or unexported fields
}

ManageCompatibility is the admin-facing CRUD use case for compatibility matrices. F8-Phase5 (재개) brings matrix Create/Update/Delete behind a use case so validation lives in one place and cache invalidation is triggered consistently.

func NewManageCompatibility

func NewManageCompatibility(repo port.CompatibilityRepository, opts ...ManageCompatibilityOption) *ManageCompatibility

NewManageCompatibility constructs the use case.

func (*ManageCompatibility) Create

Create validates the payload then persists via the repository. On success the verdict cache (if wired) is cleared.

func (*ManageCompatibility) Delete

func (u *ManageCompatibility) Delete(ctx context.Context, id string) error

Delete is idempotent at the repo level; the verdict cache is still cleared so cached verdicts that referenced the deleted matrix don't linger.

func (*ManageCompatibility) Update

Update validates and persists a full replacement. NotFound from the repo surfaces unchanged so handlers can map to 404.

type ManageCompatibilityOption

type ManageCompatibilityOption func(*ManageCompatibility)

ManageCompatibilityOption configures optional dependencies.

func WithVerdictCacheClearer

func WithVerdictCacheClearer(c VerdictCacheClearer) ManageCompatibilityOption

WithVerdictCacheClearer wires the verdict cache so any successful mutation invalidates cached verdicts. Nil-safe in NewManageCompatibility.

type ManageHistory

type ManageHistory struct {
	// contains filtered or unexported fields
}

ManageHistory provides use-case operations for stack version history.

func NewManageHistory

func NewManageHistory(repo port.HistoryRepository) *ManageHistory

NewManageHistory constructs a ManageHistory use case.

func (*ManageHistory) GetDiff

func (uc *ManageHistory) GetDiff(ctx context.Context, input GetDiffInput) (*GetDiffOutput, error)

GetDiff returns the field-level diff between a version and its predecessor.

func (*ManageHistory) ListVersions

func (uc *ManageHistory) ListVersions(ctx context.Context, input ListVersionsInput) (*ListVersionsOutput, error)

ListVersions returns all versions for a stack ordered by version number.

func (*ManageHistory) SaveVersion

func (uc *ManageHistory) SaveVersion(ctx context.Context, input SaveVersionInput) (*SaveVersionOutput, error)

SaveVersion creates and persists a new version snapshot for a stack. The version number is derived from the current count of existing versions + 1.

type ManageReleaseValues

type ManageReleaseValues struct {
	// contains filtered or unexported fields
}

ManageReleaseValues 는 배포된 릴리스의 values 를 읽고 다시 적용한다.

func NewManageReleaseValues

func NewManageReleaseValues(
	stackRepo port.StackRepository,
	kubeconfigProvider port.KubeconfigProvider,
	managerFactory ReleaseManagerFactory,
	opts ...ManageReleaseValuesOption,
) *ManageReleaseValues

NewManageReleaseValues 는 유스케이스를 조립한다.

func (*ManageReleaseValues) Apply

Apply 는 편집본을 클러스터에 적용하고 스택 설정에 반영한다.

순서가 중요하다. helm upgrade 가 먼저다 — 적용에 실패한 설정이 DB 에 남으면 다음 재배포가 검증된 적 없는 값을 들고 나간다.

func (*ManageReleaseValues) GetValues

GetValues 는 선택한 모드에 맞는 편집 원본을 돌려준다.

func (*ManageReleaseValues) ListReleases

func (uc *ManageReleaseValues) ListReleases(ctx context.Context, stackID string) ([]port.ReleaseInfo, error)

ListReleases 는 스택 네임스페이스에 올라가 있는 Helm 릴리스를 돌려준다.

type ManageReleaseValuesOption

type ManageReleaseValuesOption func(*ManageReleaseValues)

ManageReleaseValuesOption 은 선택 의존성을 주입한다.

func WithReleaseValuesHistory

func WithReleaseValuesHistory(history *ManageHistory) ManageReleaseValuesOption

WithReleaseValuesHistory 를 붙이면 적용 직전 설정이 이력으로 남는다.

type MemoryVerdictCache

type MemoryVerdictCache struct {
	// contains filtered or unexported fields
}

MemoryVerdictCache is an in-process TTL cache. sync.Map keeps the lookup path lock-free; expired entries are removed lazily on Get.

func NewMemoryVerdictCache

func NewMemoryVerdictCache(ttl time.Duration) *MemoryVerdictCache

NewMemoryVerdictCache builds a cache with the given TTL. A zero or negative TTL disables the cache (Get always misses).

func (*MemoryVerdictCache) Clear

func (c *MemoryVerdictCache) Clear()

Clear drops every cached entry. F8-Phase5 matrix CRUD calls this after any Create/Update/Delete succeeds, since changing a matrix can affect every cached verdict regardless of stack or cluster.

func (*MemoryVerdictCache) Get

Get returns a cached verdict when present and not yet expired.

func (*MemoryVerdictCache) Invalidate

func (c *MemoryVerdictCache) Invalidate(prefix string)

Invalidate drops entries whose key starts with prefix. Passing an empty prefix clears the entire cache — the initial implementation's simple invalidation strategy.

func (*MemoryVerdictCache) Put

Put stores a verdict under key with the configured TTL.

type ReapStaleInstalls

type ReapStaleInstalls struct {
	// contains filtered or unexported fields
}

ReapStaleInstalls 는 끊긴 설치를 실패로 표시한다.

설치는 API 프로세스 안의 고루틴이 돌린다. 파드가 교체되면 그 고루틴이 사라지고 아무도 실패를 기록하지 않는다 — 스택은 installing 인 채로 영원히 남는다. 그 상태에서는 이어서 진행(continue)조차 막히므로(failed/pending 만 허용) 사용자에게는 지우고 다시 까는 길밖에 없다. 2026-08-20 운영에서 실제로 그렇게 갇혔고, 몇 시간 뒤에야 발견됐다.

살아 있는 설치와 구분할 방법은 시간뿐이다. 레플리카가 여럿인 환경에서는 "이 프로세스가 안 돌리고 있다" 가 "아무도 안 돌리고 있다" 를 뜻하지 않는다.

func NewReapStaleInstalls

func NewReapStaleInstalls(stacks port.StackRepository) *ReapStaleInstalls

func (*ReapStaleInstalls) Run

func (uc *ReapStaleInstalls) Run(ctx context.Context) (int, error)

Run 은 한 번 훑고 끊긴 설치를 실패로 옮긴다. 옮긴 개수를 돌려준다.

type ReleaseManagerFactory

type ReleaseManagerFactory func(kubeconfig []byte) port.HelmReleaseManager

ReleaseManagerFactory 는 대상 클러스터의 kubeconfig 로 릴리스 관리자를 만든다.

type ReleaseValuesMode

type ReleaseValuesMode string

ReleaseValuesMode 는 편집 단위를 고른다.

const (
	// ReleaseValuesModeLive 는 배포된 values 전체를 편집한다.
	ReleaseValuesModeLive ReleaseValuesMode = "live"
	// ReleaseValuesModeOverride 는 사용자 오버라이드만 편집한다.
	ReleaseValuesModeOverride ReleaseValuesMode = "override"
)

type ReleaseValuesOutput

type ReleaseValuesOutput struct {
	ReleaseName string            `json:"release_name"`
	StepName    string            `json:"step_name,omitempty"`
	Namespace   string            `json:"namespace"`
	Revision    int               `json:"revision"`
	Mode        ReleaseValuesMode `json:"mode"`
	YAML        string            `json:"yaml"`
	// ProtectedPaths 는 이 릴리스에서 플랫폼이 소유한 경로다. 에디터가 미리
	// 표시해 두면 사용자가 건드리기 전에 알 수 있다.
	ProtectedPaths []string `json:"protected_paths,omitempty"`
}

ReleaseValuesOutput 은 에디터에 실어 줄 YAML 과 그 출처다.

type ResourceCostBreakdown

type ResourceCostBreakdown struct {
	CPUCostUSD     float64
	MemoryCostUSD  float64
	StorageCostUSD float64
}

type SaveVersionInput

type SaveVersionInput struct {
	StackID      string
	Config       domain.StackConfig
	ChangedBy    string
	ChangeReason string
}

SaveVersionInput holds parameters for saving a new stack version snapshot.

type SaveVersionOutput

type SaveVersionOutput struct {
	Version *domain.StackVersion
}

SaveVersionOutput holds the result of saving a stack version.

type SourceControlCredentials

type SourceControlCredentials struct {
	// PersonalAccessToken 은 GitHub PAT 다 (repo·workflow·read:packages).
	PersonalAccessToken string
}

SourceControlCredentials 는 설치 요청이 들고 온 외부 SCM 자격증명이다.

stacks.config 를 거치지 않는다 — 그 구조는 평문 JSONB 로 저장되므로 토큰이 들어가면 DB 를 읽을 수 있는 누구에게나 노출된다. 배포 요청에서 받아 이 구조로 들고 다니다가 OpenBao 에만 기록한다.

type ToolInstance

type ToolInstance struct {
	Name      string
	Instances int
}

ToolInstance specifies a tool and how many instances to run.

type ToolResourceEstimate

type ToolResourceEstimate struct {
	Name      string
	Instances int
	CPUCores  float64
	MemoryGi  float64
	StorageGi float64
}

ToolResourceEstimate holds the per-tool resource breakdown.

type UpdateStack

type UpdateStack struct {
	// contains filtered or unexported fields
}

UpdateStack permits in-place edits of stacks in state pending or failed. The prior config is snapshotted to HistoryRepository before the mutation lands so operators can rollback via the existing /rollback endpoint.

func NewUpdateStack

func NewUpdateStack(stackRepo port.StackRepository, manageHistory *ManageHistory) *UpdateStack

NewUpdateStack wires the usecase. manageHistory may be nil — when absent, the usecase still updates but does not record history.

func (*UpdateStack) Execute

func (uc *UpdateStack) Execute(ctx context.Context, input UpdateStackInput) (*UpdateStackOutput, error)

Execute applies the requested fields to the stack. Returns STACK_UPDATE_INVALID_STATE-shaped errors so the handler layer can map to HTTP 409 without string matching.

type UpdateStackInput

type UpdateStackInput struct {
	StackID   string
	Name      *string
	ClusterID *string
	Namespace *string
	Config    *domain.StackConfig
	Tools     []domain.ToolConfig
}

UpdateStackInput holds the parameters for mutating an existing stack that hasn't yet completed installation. F8 follow-up Phase 4: closes the "orphan stack" gap where F8-F3's createStack → validate → fail flow left a persisted stack with no way to amend tools and resubmit.

type UpdateStackOutput

type UpdateStackOutput struct {
	Stack *domain.Stack
}

UpdateStackOutput returns the updated stack for easy chaining.

type UpsertResourceDefault

type UpsertResourceDefault struct {
	// contains filtered or unexported fields
}

func (*UpsertResourceDefault) Execute

type UpsertResourceDefaultInput

type UpsertResourceDefaultInput struct {
	ToolKey          string
	DisplayName      string
	CPURequest       float64
	CPULimit         float64
	MemoryRequestGi  float64
	MemoryLimitGi    float64
	StorageRequestGi float64
	StorageLimitGi   float64
	IsDefault        bool
}

type UpsertResourceDefaultOutput

type UpsertResourceDefaultOutput struct {
	Item *domain.ResourceDefault
}

type ValidateCompatibility

type ValidateCompatibility struct {
	// contains filtered or unexported fields
}

ValidateCompatibility checks whether a given tool combination matches a known matrix.

func NewValidateCompatibility

func NewValidateCompatibility(repo port.CompatibilityRepository, opts ...ValidateCompatibilityOption) *ValidateCompatibility

NewValidateCompatibility constructs a ValidateCompatibility use case.

func (*ValidateCompatibility) Execute

Execute validates the tool combination and returns the matching matrix if found.

type ValidateCompatibilityInput

type ValidateCompatibilityInput struct {
	// Tools maps tool category to tool name, e.g. {"ci_platform": "GitLab CI"}.
	Tools map[string]string

	// StackID, when set with empty Tools, triggers persisted mode: load the
	// stack from StackRepository, derive tools from stack.Tools, and fall
	// back to stack.ClusterID when ClusterID is empty.
	StackID string

	// ClusterID, when set, instructs the use case to resolve cluster node
	// architectures from the admin bounded context via ClusterReader. Takes
	// precedence over NodeArchitectures.
	ClusterID string

	// NodeArchitectures is the explicit override. Callers who already have
	// the fleet arch list (e.g. on-the-fly validation in the wizard before
	// a cluster row exists) should populate this directly.
	NodeArchitectures []string
}

ValidateCompatibilityInput holds the tool combination to validate, plus optional target-cluster context the Pre-Deploy Gate uses to cross-check per-tool `ArchSupport` against the actual worker fleet.

Two call modes are supported:

  • Explicit mode: Tools is non-empty. The caller supplies the combination directly (wizard pre-deploy preview, ad-hoc API calls).
  • Persisted mode: Tools is empty and StackID is set. The use case loads the stack via StackRepository and derives tools + ClusterID fallback from the persisted aggregate. Used by the Deploy handler's server-side gate so a stack can't skip verification by bypassing the UI.

Explicit input wins when both are provided — a caller passing tools is asking about a specific combination and shouldn't be overridden by the stack's current persisted state.

type ValidateCompatibilityOption

type ValidateCompatibilityOption func(*ValidateCompatibility)

ValidateCompatibilityOption configures optional dependencies.

func WithClusterReader

func WithClusterReader(r port.ClusterReader) ValidateCompatibilityOption

WithClusterReader wires a ClusterReader so the Pre-Deploy Gate can resolve node architectures from a cluster_id instead of requiring the caller to pass NodeArchitectures explicitly.

func WithStackRepository

func WithStackRepository(r port.StackRepository) ValidateCompatibilityOption

WithStackRepository enables persisted mode: when Execute receives an input with empty Tools but a non-empty StackID, the use case loads the stack row and derives tools + ClusterID fallback from it. The Deploy handler uses this to run the gate server-side after stack creation so the UI cannot bypass arch / tier checks.

func WithVerdictCache

func WithVerdictCache(cache VerdictCache) ValidateCompatibilityOption

WithVerdictCache wires a short-TTL cache in front of Execute. Repeat calls with the same (stack_id, cluster_id, node_architectures, tools) tuple return the previously computed verdict without touching the repository until the entry expires or is invalidated.

type ValidateCompatibilityOutput

type ValidateCompatibilityOutput struct {
	Compatible        bool
	Matrix            *domain.CompatibilityMatrix
	Message           string
	Overall           ValidationOverall
	Issues            []ValidationIssue
	NodeArchitectures []string
	CheckedAt         time.Time
}

ValidateCompatibilityOutput holds the result of a compatibility validation.

type ValidationIssue

type ValidationIssue struct {
	Tool     string `json:"tool"`
	Message  string `json:"message"`
	Severity string `json:"severity"`
	Code     string `json:"code,omitempty"`
}

ValidationIssue represents a detailed compatibility finding.

type ValidationOverall

type ValidationOverall struct {
	State string `json:"state"`
	Score int    `json:"score"`
}

ValidationOverall represents the rolled-up compatibility state.

type VerdictCache

type VerdictCache interface {
	Get(key string) (*ValidateCompatibilityOutput, bool)
	Put(key string, out *ValidateCompatibilityOutput)
	// Invalidate evicts all entries whose key starts with the given prefix.
	// Used when stack/cluster/matrix state changes; callers can also pass
	// an empty string to blow the whole cache (the initial implementation
	// uses a simple full-clear to avoid prefix-matching complexity).
	Invalidate(prefix string)
}

VerdictCache is the interface ValidateCompatibility consults before running the actual matrix match + arch check. Phase 6 of the F8 follow-up: the Install Wizard re-submits after every edit, and identical (stack tools, cluster, matrix set) tuples produce identical verdicts, so a short-TTL cache cuts duplicate work.

Implementations MUST be safe for concurrent use — Get and Put can be called from multiple goroutines on shared keys.

type VerdictCacheClearer

type VerdictCacheClearer interface {
	Clear()
}

VerdictCacheClearer is the minimal cache invalidator the ManageCompatibility use case calls after CRUD mutations. Implemented by *MemoryVerdictCache via its Clear() method (added alongside this use case).

type WorkloadInput

type WorkloadInput struct {
	Developers        int
	ConcurrentRunners int
	WeeklyCommits     int
	BuildFrequency    string // hourly, daily, on-push
}

WorkloadInput describes the workload characteristics.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL