adapters

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultCacheMaximumSize is the default maximum number of items in the cache.
	DefaultCacheMaximumSize = 10_000
	// DefaultCacheExpiry is the default expiration time for cache entries.
	DefaultCacheExpiry = 24 * time.Hour
)

Cache configuration constants.

View Source
const (
	// HTTPDefaultTimeout is the default request timeout.
	HTTPDefaultTimeout = 30 * time.Second
	// HTTPDefaultRetryCount is the default number of retry attempts.
	HTTPDefaultRetryCount = 3
	// HTTPDefaultRetryWaitTime is the default wait time between retries.
	HTTPDefaultRetryWaitTime = 1 * time.Second
	// HTTPDefaultRetryMaxWaitTime is the default maximum wait time between retries.
	HTTPDefaultRetryMaxWaitTime = 10 * time.Second
	// HTTPClientErrorMinStatus is the minimum status code for client errors (4xx).
	HTTPClientErrorMinStatus = 400
	// HTTPServerErrorMinStatus is the minimum status code for server errors (5xx).
	HTTPServerErrorMinStatus = 500
)
View Source
const (
	// NixDryRunStoreSizeGB is the estimated Nix store size for dry-run mode.
	NixDryRunStoreSizeGB = 50
	// NixGCPostDelay is the delay after garbage collection to allow async operations.
	NixGCPostDelay = 500 * time.Millisecond
	// NixDryRunGenerationSizeMB is the estimated size per generation in dry-run mode.
	NixDryRunGenerationSizeMB = 50
	// NixDryRunGCSizeMB is the estimated size freed from GC in dry-run mode.
	NixDryRunGCSizeMB = 100

	// NixGenerationMinFields is the minimum number of fields expected in generation output.
	NixGenerationMinFields = 3
)
View Source
const DefaultTimeout = 5 * time.Minute

DefaultTimeout is the default timeout for external commands.

Variables

This section is empty.

Functions

func ErrCacheMiss

func ErrCacheMiss(key string) error

ErrCacheMiss creates a cache miss error.

func ErrForbidden

func ErrForbidden(operation string) error

ErrForbidden creates a forbidden error.

func ErrHTTPError

func ErrHTTPError(statusCode int, message string) error

ErrHTTPError creates an HTTP error.

func ErrInvalidArgument

func ErrInvalidArgument(arg, message string) error

ErrInvalidArgument creates an argument validation error.

func ErrInvalidConfig

func ErrInvalidConfig(message string) error

ErrInvalidConfig creates a configuration validation error.

func ErrNotFound

func ErrNotFound(resource string) error

ErrNotFound creates a not found error.

func ErrNotImplemented

func ErrNotImplemented(feature string) error

ErrNotImplemented creates a not implemented error.

func ErrRateLimit

func ErrRateLimit(limit float64) error

ErrRateLimit creates a rate limit error.

func ErrServiceUnavailable

func ErrServiceUnavailable(service string) error

ErrServiceUnavailable creates a service unavailable error.

func ErrTimeout

func ErrTimeout(operation string) error

ErrTimeout creates a timeout error.

func ErrUnauthorized

func ErrUnauthorized(operation string) error

ErrUnauthorized creates an unauthorized error.

func ExecWithDefaultTimeout

func ExecWithDefaultTimeout(ctx context.Context, name string, args ...string) *exec.Cmd

ExecWithDefaultTimeout creates a command with the default 5-minute timeout. If the context already has a deadline, respects the existing deadline.

func ExecWithTimeout

func ExecWithTimeout(
	ctx context.Context,
	timeout time.Duration,
	name string,
	args ...string,
) *exec.Cmd

ExecWithTimeout creates a command with the specified timeout. If the context already has a deadline, respects the earlier deadline.

func GetEnvBool

func GetEnvBool(key string, defaultValue bool) bool

GetEnvBool returns boolean environment variable with default.

func GetEnvDuration

func GetEnvDuration(key string, defaultValue time.Duration) time.Duration

GetEnvDuration returns duration environment variable with default.

func GetEnvInt

func GetEnvInt(key string, defaultValue int) int

GetEnvInt returns integer environment variable with default.

func GetEnvWithDefault

func GetEnvWithDefault(key, defaultValue string) string

GetEnvWithDefault returns environment variable with default value.

Types

type AppSettings

type AppSettings struct {
	Debug       bool   `env:"DEBUG"     envDefault:"false"`
	Environment string `env:"ENV"       envDefault:"development"`
	LogLevel    string `env:"LOG_LEVEL" envDefault:"info"`
	Version     string `env:"VERSION"   envDefault:"dev"`
}

AppSettings holds application-level configuration.

type CacheManager

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

CacheManager provides in-memory caching functionality.

func NewCacheManager

func NewCacheManager(defaultExpiration, cleanupInterval time.Duration) *CacheManager

NewCacheManager creates a new cache manager defaultExpiration: default TTL for cache entries cleanupInterval: interval for cleaning expired entries.

func (*CacheManager) Clear

func (cm *CacheManager) Clear()

Clear removes all items from cache.

func (*CacheManager) Delete

func (cm *CacheManager) Delete(key string)

Delete removes an item from cache.

func (*CacheManager) FlushExpired

func (cm *CacheManager) FlushExpired()

FlushExpired removes all expired items by iterating and checking.

func (*CacheManager) Get

func (cm *CacheManager) Get(key string) (any, bool)

Get retrieves a value from cache.

func (*CacheManager) GetWithExpiration

func (cm *CacheManager) GetWithExpiration(key string) (any, time.Time, bool)

GetWithExpiration retrieves a value with its expiration time.

func (*CacheManager) ItemCount

func (cm *CacheManager) ItemCount() int

ItemCount returns the number of items in cache.

func (*CacheManager) Set

func (cm *CacheManager) Set(key string, value any, expiration time.Duration)

Set stores a value in cache with expiration.

func (*CacheManager) Stats

func (cm *CacheManager) Stats() CacheStats

Stats returns cache performance statistics.

type CacheSettings

type CacheSettings struct {
	Enabled         bool          `env:"CACHE_ENABLED"          envDefault:"true"`
	TTL             time.Duration `env:"CACHE_TTL"              envDefault:"5m"`
	CleanupInterval time.Duration `env:"CACHE_CLEANUP_INTERVAL" envDefault:"10m"`
}

CacheSettings holds cache-related configuration.

type CacheStats

type CacheStats struct {
	Items     int     `json:"items"`
	HitCount  uint64  `json:"hitCount"`
	MissCount uint64  `json:"missCount"`
	HitRate   float64 `json:"hitRate"`
}

CacheStats provides cache statistics.

type DiskSettings

type DiskSettings struct {
	MaxUsagePercent   int `env:"MAX_DISK_USAGE_PERCENT" envDefault:"50"`
	MinUsagePercent   int `env:"MIN_DISK_USAGE_PERCENT" envDefault:"10"`
	RoundingIncrement int `env:"ROUNDING_INCREMENT"     envDefault:"10"`
}

DiskSettings holds disk usage configuration.

type EnvironmentConfig

type EnvironmentConfig struct {
	App         AppSettings
	Performance PerformanceSettings
	Cache       CacheSettings
	HTTP        HTTPSettings
	Nix         NixSettings
	Disk        DiskSettings
	Security    SecuritySettings
	Filesystem  FilesystemSettings
	Monitoring  MonitoringSettings
}

EnvironmentConfig holds environment-based configuration using composition.

func LoadEnvironmentConfig

func LoadEnvironmentConfig() (*EnvironmentConfig, error)

LoadEnvironmentConfig loads configuration from environment variables.

func LoadEnvironmentConfigWithPrefix

func LoadEnvironmentConfigWithPrefix(prefix string) (*EnvironmentConfig, error)

LoadEnvironmentConfigWithPrefix loads configuration with custom prefix.

func (*EnvironmentConfig) ToMap

func (cfg *EnvironmentConfig) ToMap() map[string]any

ToMap converts config to map for legacy compatibility (deprecated).

func (*EnvironmentConfig) ToView

ToView converts config to strongly-typed view for logging/debugging.

func (*EnvironmentConfig) ValidateEnvironmentConfig

func (cfg *EnvironmentConfig) ValidateEnvironmentConfig() error

ValidateEnvironmentConfig validates the loaded configuration.

type EnvironmentConfigView

type EnvironmentConfigView struct {
	Debug               bool          `json:"debug"`
	Environment         string        `json:"environment"`
	LogLevel            string        `json:"logLevel"`
	Version             string        `json:"version"`
	MaxConcurrency      int           `json:"maxConcurrency"`
	Timeout             time.Duration `json:"timeout"`
	RateLimitRPS        float64       `json:"rateLimitRps"`
	CacheEnabled        bool          `json:"cacheEnabled"`
	CacheTTL            time.Duration `json:"cacheTtl"`
	HTTPTimeout         time.Duration `json:"httpTimeout"`
	NixPath             string        `json:"nixPath"`
	MaxNixGenerations   int           `json:"maxNixGenerations"`
	SafeMode            bool          `json:"safeMode"`
	RequireConfirmation bool          `json:"requireConfirmation"`
	TempDir             string        `json:"tempDir"`
	ConfigFile          string        `json:"configFile"`
	StateDirectory      string        `json:"stateDirectory"`
}

EnvironmentConfigView provides strongly-typed config representation for logging/debugging.

type FilesystemSettings

type FilesystemSettings struct {
	TempDir        string `env:"TEMP_DIR"        envDefault:"/tmp"`
	ConfigFile     string `env:"CONFIG_FILE"     envDefault:"clean-wizard.yaml"`
	StateDirectory string `env:"STATE_DIRECTORY" envDefault:"~/.clean-wizard"`
}

FilesystemSettings holds filesystem paths configuration.

type HTTPClient

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

HTTPClient provides a modern HTTP client with built-in features.

func NewHTTPClient

func NewHTTPClient() *HTTPClient

NewHTTPClient creates a new HTTP client with sensible defaults.

func (*HTTPClient) Delete

func (hc *HTTPClient) Delete(ctx context.Context, url string) (*HTTPResponse, error)

Delete performs HTTP DELETE request.

func (*HTTPClient) Get

func (hc *HTTPClient) Get(ctx context.Context, url string) (*HTTPResponse, error)

Get performs HTTP GET request.

func (*HTTPClient) Post

func (hc *HTTPClient) Post(ctx context.Context, url string, body any) (*HTTPResponse, error)

Post performs HTTP POST request.

func (*HTTPClient) Put

func (hc *HTTPClient) Put(ctx context.Context, url string, body any) (*HTTPResponse, error)

Put performs HTTP PUT request.

func (*HTTPClient) WithAuth

func (hc *HTTPClient) WithAuth(authType, token string) *HTTPClient

WithAuth sets authentication header.

func (*HTTPClient) WithHeader

func (hc *HTTPClient) WithHeader(key, value string) *HTTPClient

WithHeader adds a default header.

func (*HTTPClient) WithRetry

func (hc *HTTPClient) WithRetry(count int, waitTime, maxWaitTime time.Duration) *HTTPClient

WithRetry configures retry behavior.

func (*HTTPClient) WithTimeout

func (hc *HTTPClient) WithTimeout(timeout time.Duration) *HTTPClient

WithTimeout sets the request timeout.

type HTTPResponse

type HTTPResponse struct {
	StatusCode int                 `json:"statusCode"`
	Body       string              `json:"body"`
	Headers    map[string][]string `json:"headers"`
	Request    *resty.Request      `json:"request"`
}

HTTPResponse wraps resty response.

func (*HTTPResponse) IsClientError

func (hr *HTTPResponse) IsClientError() bool

IsClientError returns true if status code indicates client error (4xx).

func (*HTTPResponse) IsError

func (hr *HTTPResponse) IsError() bool

IsError returns true if status code indicates error (4xx, 5xx).

func (*HTTPResponse) IsServerError

func (hr *HTTPResponse) IsServerError() bool

IsServerError returns true if status code indicates server error (5xx).

func (*HTTPResponse) IsSuccess

func (hr *HTTPResponse) IsSuccess() bool

IsSuccess returns true if status code indicates success (2xx).

type HTTPSettings

type HTTPSettings struct {
	Timeout       time.Duration `env:"HTTP_TIMEOUT"         envDefault:"30s"`
	RetryCount    int           `env:"HTTP_RETRY_COUNT"     envDefault:"3"`
	RetryWaitTime time.Duration `env:"HTTP_RETRY_WAIT_TIME" envDefault:"1s"`
	RetryMaxWait  time.Duration `env:"HTTP_RETRY_MAX_WAIT"  envDefault:"10s"`
}

HTTPSettings holds HTTP client configuration.

type MonitoringSettings

type MonitoringSettings struct {
	MetricsEnabled  bool   `env:"METRICS_ENABLED"  envDefault:"false"`
	MetricsPort     int    `env:"METRICS_PORT"     envDefault:"8080"`
	MetricsPath     string `env:"METRICS_PATH"     envDefault:"/metrics"`
	TracingEnabled  bool   `env:"TRACING_ENABLED"  envDefault:"false"`
	TracingEndpoint string `env:"TRACING_ENDPOINT" envDefault:""`
}

MonitoringSettings holds monitoring and observability configuration.

type NixAdapter

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

NixAdapter wraps Nix package manager operations.

func NewNixAdapter

func NewNixAdapter(timeout time.Duration, retries int) *NixAdapter

NewNixAdapter creates Nix adapter with configuration.

func (*NixAdapter) CollectGarbage

func (n *NixAdapter) CollectGarbage(ctx context.Context) result.Result[domain.CleanResult]

CollectGarbage removes old Nix generations. In dry-run mode, returns a success result without actually running garbage collection.

func (*NixAdapter) GetStoreSize

func (n *NixAdapter) GetStoreSize(ctx context.Context) result.Result[int64]

GetStoreSize returns Nix store size with dry-run isolation.

func (*NixAdapter) IsAvailable

func (n *NixAdapter) IsAvailable(ctx context.Context) bool

IsAvailable checks if Nix is available and accessible.

func (*NixAdapter) ListGenerations

func (n *NixAdapter) ListGenerations(ctx context.Context) result.Result[[]domain.NixGeneration]

ListGenerations lists Nix generations. In dry-run mode, still lists real generations but won't actually delete them.

func (*NixAdapter) ParseGeneration

func (n *NixAdapter) ParseGeneration(line string) (domain.NixGeneration, error)

ParseGeneration parses generation line from nix-env output. Expected format when using --list-generations (without --profile):

"32   2026-01-12 08:03:14"
"33   2026-01-15 21:14:05   (current)"

func (*NixAdapter) RemoveGeneration

func (n *NixAdapter) RemoveGeneration(
	ctx context.Context,
	genID domain.NixGenerationID,
) result.Result[domain.CleanResult]

RemoveGeneration removes specific Nix generation. In dry-run mode, returns a success result without actually deleting.

func (*NixAdapter) SetDryRun

func (n *NixAdapter) SetDryRun(dryRun bool)

SetDryRun configures dry-run mode for the adapter.

type NixSettings

type NixSettings struct {
	Path               string `env:"NIX_PATH"                envDefault:"/nix/var/nix"`
	MaxGenerations     int    `env:"MAX_NIX_GENERATIONS"     envDefault:"10"`
	DefaultGenerations int    `env:"DEFAULT_NIX_GENERATIONS" envDefault:"3"`
	StoreSizeGB        int    `env:"NIX_STORE_SIZE_GB"       envDefault:"300"`
}

NixSettings holds Nix-specific configuration.

type PerformanceSettings

type PerformanceSettings struct {
	MaxConcurrency int           `env:"MAX_CONCURRENCY" envDefault:"4"`
	Timeout        time.Duration `env:"TIMEOUT"         envDefault:"30s"`
	RateLimitRPS   float64       `env:"RATE_LIMIT_RPS"  envDefault:"10"`
}

PerformanceSettings holds performance-related configuration.

type RateLimitStats

type RateLimitStats struct {
	Limit  rate.Limit `json:"limit"`
	Burst  int        `json:"burst"`
	Tokens float64    `json:"tokens"`
}

RateLimitStats provides rate limiting statistics.

type RateLimiter

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

RateLimiter provides rate limiting functionality for cleaning operations.

func NewRateLimiter

func NewRateLimiter(rps float64, burst int) *RateLimiter

NewRateLimiter creates a new rate limiter rps: requests per second limit burst: maximum burst size

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow() bool

Allow returns true if the operation is allowed immediately.

func (*RateLimiter) Reservation

func (rl *RateLimiter) Reservation() *rate.Reservation

Reservation returns a reservation for a future operation.

func (*RateLimiter) Stats

func (rl *RateLimiter) Stats() RateLimitStats

Stats returns current rate limiter statistics.

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context) error

Wait blocks until the operation is allowed or context is cancelled.

type SecuritySettings

type SecuritySettings struct {
	SafeMode            bool `env:"SAFE_MODE"            envDefault:"true"`
	RequireConfirmation bool `env:"REQUIRE_CONFIRMATION" envDefault:"true"`
}

SecuritySettings holds security-related configuration.

Jump to

Keyboard shortcuts

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