usecase

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 27 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 ErrImageScanInProgress = errors.New("이 스택의 설치 이미지 스캔이 이미 진행 중입니다")

ErrImageScanInProgress 는 같은 스택의 스캔이 이미 돌고 있다는 뜻이다.

View Source
var ErrImportConfirmationRequired = errors.New("import confirmation required")
View Source
var ErrStackImageScanNotFound = errors.New("이 스택에서 그 이미지의 스캔 결과를 찾지 못했습니다")

ErrStackImageScanNotFound 는 그 이미지의 스캔 결과가 없다는 뜻이다.

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 BundleOption added in v0.6.0

type BundleOption func(*ManageUpgradeBundles)

func WithBundleClock added in v0.6.0

func WithBundleClock(now func() time.Time) BundleOption

WithBundleClock 은 시각을 바꿔 넣는다(테스트).

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) SetReleaseManagerFactory added in v0.6.0

func (uc *DeleteStack) SetReleaseManagerFactory(factory ReleaseManagerFactory)

SetReleaseManagerFactory 는 공용 릴리스의 values 를 읽을 실행기를 주입한다.

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 EnsureSharedComponents added in v0.6.0

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

EnsureSharedComponents 는 클러스터 공용 컨트롤러 — cert-manager·metrics-server — 를 스택 없이 세운다.

클러스터의 마지막 스택을 지우면 delete_shared_resources 가 두 컨트롤러와 내부 CA·Gateway CRD 를 회수한다. 백업은 CA·CRD 같은 **자원**은 담지만 컨트롤러는 **설치물**이라 담지 않는다. 그래서 그 뒤의 복구는 cert-manager 가 없어 ClusterIssuer·Certificate 를 되살리지 못했고, 운영자가 손으로 먼저 깔아야 했다(백업복구 설계 §11.3 Q16). 이 유스케이스가 그 손작업을 대신한다 — 설치기의 같은 단계를 그대로 돌리므로 설치와 복구가 한 코드로 같은 결과를 낸다.

스택 ID 를 비우고 부른다. 설치기는 스택 ID 가 비면 단계 순서 검사를 하지 않고, 이미 깔린 cert-manager 가 있으면 다시 쓴다 — 다른 스택이 쓰는 클러스터에 두 번째로 불러도 안전하다. 백업 모듈이 복구 중 공용 자원을 되살리기 직전에 부른다.

func NewEnsureSharedComponents added in v0.6.0

func NewEnsureSharedComponents(factory func(kubeconfig []byte) port.StepExecutor) *EnsureSharedComponents

NewEnsureSharedComponents 는 설치기 팩토리로 유스케이스를 만든다. 스택 설치가 쓰는 것과 같은 팩토리를 넘겨야 차트 메타데이터·자원 기본값·이미지 프로젝트가 설치와 같다.

func (*EnsureSharedComponents) EnsureSharedComponents added in v0.6.0

func (uc *EnsureSharedComponents) EnsureSharedComponents(ctx context.Context, kubeconfig []byte, namespace string) ([]string, []string, error)

EnsureSharedComponents 는 돌린 단계와 넘긴 실패를 돌려준다. cert-manager 실패는 오류다 — 그것 없이는 내부 CA 를 되살릴 수 없고, 되살리지 못한 채 볼륨까지 되돌리면 되돌릴 길이 없다. metrics-server 는 HPA·자원 지표에만 쓰이므로 실패해도 경고로 넘긴다.

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 GatewayAddressReaderFactory added in v0.6.0

type GatewayAddressReaderFactory func(kubeconfig []byte) (port.GatewayAddressReader, error)

GatewayAddressReaderFactory 는 대상 클러스터의 kubeconfig 로 게이트웨이 주소 조회기를 만든다.

type GatewayAliasRepin added in v0.6.0

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

GatewayAliasRepin 은 스택 게이트웨이의 지금 주소로 러너·Argo CD 의 hostAliases 를 다시 박는다.

설치는 게이트웨이 ClusterIP 를 두 릴리스의 values 에 박는다(스택 도구 이름은 클러스터 안에서 아무도 풀어 주지 않는다). 복구로 그 주소가 바뀌면 — 다른 클러스터로 되돌렸거나, ClusterIP 를 담지 않은 옛 백업이거나 — 두 곳 모두 옛 주소를 가리켜 CI 는 clone 에서, Argo CD 는 매니페스트 조회에서 멈춘다. 백업 모듈이 복구 끝에 이것을 부른다.

values 만 바꿔 다시 적용한다. 차트는 릴리스에 저장된 것을 쓰고, 서브차트를 잃은 차트(argo-cd)는 같은 버전을 저장소에서 다시 받는다(release-values.go chartForRelease). 그래야 릴리스 Secret·러너 ConfigMap·Argo CD 파드가 함께 맞고, 나중에 values 를 고쳐도 옛 주소가 돌아오지 않는다. 주소가 그대로면 아무것도 하지 않는다. 한 릴리스가 실패해도 나머지는 맞춘다.

func NewGatewayAliasRepin added in v0.6.0

func NewGatewayAliasRepin(
	stackRepo port.StackRepository,
	kubeconfigProvider port.KubeconfigProvider,
	managerFactory ReleaseManagerFactory,
	readerFactory GatewayAddressReaderFactory,
) *GatewayAliasRepin

NewGatewayAliasRepin 은 유스케이스를 조립한다.

func (*GatewayAliasRepin) RepinGatewayAliases added in v0.6.0

func (uc *GatewayAliasRepin) RepinGatewayAliases(ctx context.Context, stackID, namespace string, kubeconfig []byte) (string, []string, error)

RepinGatewayAliases 는 네임스페이스(비우면 스택의 것)에서 게이트웨이 주소를 읽어 러너·Argo CD 의 hostAliases 를 맞춘다. 게이트웨이 주소와 다시 적용한 릴리스를 돌려준다.

kubeconfig 를 주면 그 클러스터를 본다. full 복구는 플랫폼 DB 를 백업 시점으로 되돌리므로, 그 사이 스택을 다른 클러스터로 옮겼다면 DB 의 kubeconfig 는 옛 클러스터다 — 복구가 실제로 되돌린 클러스터를 넘긴다. 비우면 스택의 클러스터에서 읽는다.

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 WithInstalledImageScan added in v0.6.0

func WithInstalledImageScan(runner installedImageScanRunner) InstallStackOption

WithInstalledImageScan 은 설치가 끝난 뒤 설치 이미지를 스캔하도록 배선한다.

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 ManageUpgradeBundles added in v0.6.0

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

ManageUpgradeBundles 는 관리자가 업그레이드 번들을 등록하고 상태를 바꾸는 유스케이스다 (설계 §12.4). 번들은 플랫폼 전체의 것이라 조직에 묶이지 않는다. 리허설 없이 실행 가능한 경로가 생기지 않도록, verified 는 운영자의 리허설 확인이 있을 때만 된다 — 그 규칙은 도메인이 지킨다.

func NewManageUpgradeBundles added in v0.6.0

func NewManageUpgradeBundles(bundles port.UpgradeBundleStore, opts ...BundleOption) *ManageUpgradeBundles

func (*ManageUpgradeBundles) ChangeStatus added in v0.6.0

func (uc *ManageUpgradeBundles) ChangeStatus(ctx context.Context, id, status string, rehearsalConfirmed bool) (*domain.UpgradeBundle, error)

ChangeStatus 는 번들 상태를 바꾼다. verified 로 올릴 때는 리허설 확인이 필요하다.

func (*ManageUpgradeBundles) List added in v0.6.0

List 는 상태와 무관하게 모든 번들을 돌려준다 — 관리 화면은 거둔 경로도 본다.

func (*ManageUpgradeBundles) Register added in v0.6.0

Register 는 번들을 검사해 저장한다. 같은 ID · 같은 경로면 domain.ErrUpgradeBundleExists.

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 RegisterUpgradeBundleInput added in v0.6.0

type RegisterUpgradeBundleInput struct {
	ID                     string
	Tool                   string
	ReleaseName            string
	ChartName              string
	RepoURL                string
	SourceChartVersion     string
	SourceAppVersion       string
	TargetChartVersion     string
	TargetAppVersion       string
	RiskLevel              string
	ExpectedDisruption     string
	ReleaseNotes           string
	RequiresBackup         bool
	SupportedArchitectures []string
	FixesCVEs              []string
	Status                 string
	RehearsalConfirmed     bool
}

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 ScanStackImages added in v0.6.0

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

ScanStackImages 는 스택이 설치한 OSS 이미지를 스캔해 보고서로 남긴다.

보고용이다 — 설치를 막지 않는다. 설치 직후 한 번, 이후 주기적으로 다시 돈다. 설치 뒤에 공개된 CVE 는 다시 스캔해야 보이기 때문이다.

func NewScanStackImages added in v0.6.0

func NewScanStackImages(
	stacks port.StackRepository,
	completed port.CompletedStackLister,
	kubeconfigs port.KubeconfigProvider,
	scanner port.InstalledImageScanner,
	results port.StackImageScanRepository,
	airgap bool,
) *ScanStackImages

NewScanStackImages 는 설치 이미지 스캔 유스케이스를 만든다.

func (*ScanStackImages) Execute added in v0.6.0

func (uc *ScanStackImages) Execute(ctx context.Context, stackID string) (*domain.StackImageScanReport, error)

Execute 는 스택 하나의 설치 이미지를 스캔하고 결과를 저장한다.

스캔할 수 없는 스택이면 스캐너를 부르지 않고 이유를 담은 보고서를 돌려준다. 스캔이 실패하면 이전 결과를 그대로 둔다 — 일시적인 장애로 보고서가 비면 알던 취약점이 사라진 것처럼 보인다.

func (*ScanStackImages) Report added in v0.6.0

func (uc *ScanStackImages) Report(ctx context.Context, stackID string) (*domain.StackImageScanReport, error)

Report 는 저장된 결과로 보고서를 만든다.

func (*ScanStackImages) ReportsForOrg added in v0.6.0

func (uc *ScanStackImages) ReportsForOrg(ctx context.Context, orgID string) ([]domain.OrgStackImageScan, error)

ReportsForOrg 는 조직의 지우지 않은 스택마다 설치 이미지 스캔 보고서를 만든다. 보안 대시보드(#65)가 스택 모듈의 공개 경로로 읽는다 — 결과 테이블(stack_image_scans)은 스택 모듈이 소유한다.

보고서는 단건 조회(Report)와 같은 조립이다. 두 곳이 따로 만들면 같은 스택이 화면마다 다른 숫자로 보인다.

func (*ScanStackImages) RescanAll added in v0.6.0

func (uc *ScanStackImages) RescanAll(ctx context.Context) int

RescanAll 은 스캔할 수 있는 모든 완료 스택을 다시 스캔하고, 성공한 수를 돌려준다.

한 스택의 실패로 나머지를 멈추지 않는다.

func (*ScanStackImages) RescanStale added in v0.6.0

func (uc *ScanStackImages) RescanStale(ctx context.Context, maxAge time.Duration) int

RescanStale 은 마지막 스캔이 maxAge 보다 오래됐거나 아직 없는 스택만 다시 스캔한다. 기동 직후에 부른다 — 주기 재스캔의 타이머는 재시작 · 롤아웃마다 처음부터 다시 세어지므로, 그것만으로는 "24시간 안에 새 CVE 를 알린다" 를 지킬 수 없다. 이미 최근에 스캔한 스택은 레플리카마다 다시 스캔하지 않는다.

func (*ScanStackImages) StackOrgID added in v0.6.0

func (uc *ScanStackImages) StackOrgID(ctx context.Context, stackID string) (string, error)

StackOrgID 는 스택이 속한 조직이다. 단건 스캔 조회가 다른 조직의 스택을 보이지 않게 쓴다 (Security Dashboard 설계 §8 G4).

func (*ScanStackImages) Vulnerabilities added in v0.6.0

func (uc *ScanStackImages) Vulnerabilities(
	ctx context.Context,
	stackID, digest string,
	filter shareddomain.VulnerabilityFilter,
) (*shareddomain.VulnerabilityPage, error)

Vulnerabilities 는 설치 이미지 하나의 취약점 목록을 조건에 맞춰 한 쪽씩 돌려준다.

스캔하지 않는 스택이면 그 이유로, 목록을 저장하지 않은 스캔이면 not_recorded 로 목록을 보일 수 없다고 답한다 — 빈 목록을 돌려주면 취약점 0건으로 읽힌다.

func (*ScanStackImages) WithNotifier added in v0.6.0

WithNotifier 는 새 CVE 고지 경로를 배선한다.

type SourceControlCredentials

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

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

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

type StartUpgradeInput added in v0.6.0

type StartUpgradeInput struct{ StackID, BundleID, RequestedBy, Reason, IdempotencyKey string }

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 UpgradeExecutorFactory added in v0.6.0

type UpgradeExecutorFactory func(kubeconfig []byte) port.ChartUpgradeExecutor

type UpgradeStack added in v0.6.0

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

UpgradeStack 은 검증된 번들로 설치된 OSS 를 올린다. 사전 점검은 요청 안에서, Helm 적용 · 상태 검사 · 되돌리기는 요청 밖에서 한다 — 화면을 닫아도 서버에서 끝난다.

func NewUpgradeStack added in v0.6.0

func NewUpgradeStack(d UpgradeStackDeps) *UpgradeStack

func (*UpgradeStack) Candidates added in v0.6.0

func (uc *UpgradeStack) Candidates(ctx context.Context, stackID string) ([]domain.UpgradeCandidate, error)

Candidates 는 스택에 실제로 설치된 릴리스(DB 가 아니라 클러스터)와 거기서 갈 수 있는 검증 경로, 마지막 실행을 돌려준다.

func (*UpgradeStack) GetRun added in v0.6.0

func (uc *UpgradeStack) GetRun(ctx context.Context, stackID, runID string) (*domain.UpgradeRun, error)

GetRun 은 실행 하나를 돌려준다. 오래 갱신이 없는 진행 중 실행은 중단으로 닫는다.

func (*UpgradeStack) ListRuns added in v0.6.0

func (uc *UpgradeStack) ListRuns(ctx context.Context, stackID string) ([]domain.UpgradeRun, error)

ListRuns 는 스택의 업그레이드 실행을 최근 것부터 돌려준다. 막힌 시도도 들어간다 — 누가 언제 무엇을 시도했고 왜 막혔는지가 감사 기록이다. 박동이 끊긴 진행 중 실행은 중단으로 닫는다.

func (*UpgradeStack) Preflight added in v0.6.0

func (uc *UpgradeStack) Preflight(ctx context.Context, stackID, bundleID string) ([]domain.UpgradeCheck, error)

Preflight 는 클러스터를 바꾸지 않고 실행 가능 여부를 점검한다.

func (*UpgradeStack) Start added in v0.6.0

Start 는 사전 점검을 거쳐 실행을 만들고, 통과했으면 Helm 적용을 백그라운드로 넘긴다. 돌려주는 실행은 upgrading(진행 중) 또는 blocked(막힘)이다 — 결과는 GetRun 으로 본다.

func (*UpgradeStack) Wait added in v0.6.0

func (uc *UpgradeStack) Wait(ctx context.Context) error

Wait 는 백그라운드 실행이 끝나기를 ctx 가 끝날 때까지 기다린다 — API 종료 처리에서 부른다.

type UpgradeStackDeps added in v0.6.0

type UpgradeStackDeps struct {
	Stacks      port.StackRepository
	Runs        port.UpgradeRepository
	Kubeconfigs port.KubeconfigProvider
	Releases    ReleaseManagerFactory
	Executors   UpgradeExecutorFactory
	// Backups 가 없으면(백업 기능 꺼짐) 백업이 필요한 번들은 막힌다 — 안전 조건을 완화하지 않는다.
	Backups      port.UpgradeBackupLookup
	BackupMaxAge time.Duration
	Health       port.UpgradeHealthVerifier
	// Vulnerabilities 는 스택의 설치 이미지 스캔 결과에서 릴리스별 CVE 를 읽는다. 없으면 후보는 번들이
	// 고치는 CVE 목록만 싣고, 그중 무엇이 이 스택에 있는지는 비운다.
	Vulnerabilities port.ReleaseVulnerabilityLookup
	Now             func() time.Time
	NewID           func() string
	// Launch 는 실행을 요청 밖으로 넘긴다. 기본은 goroutine 이다.
	Launch func(job func())
	// Context 는 API 프로세스의 수명이다. 종료 때 취소되면 Helm 이 --atomic 으로 스스로 되돌리기
	// 시작하고, 실행은 사람에게 넘긴다. 요청 ctx 와는 묶지 않는다 — 화면을 닫아도 이어진다.
	Context context.Context
	// HeartbeatInterval 은 실행 중 박동 주기다(기본 1분). domain.UpgradeHeartbeatTimeout 보다 짧아야 한다.
	HeartbeatInterval time.Duration
	// RetryBackoff 는 상태 저장 재시도의 첫 대기다(기본 1초, 두 배씩).
	RetryBackoff time.Duration
	Logger       *slog.Logger
}

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