builder

package
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package builder provides build execution for Nix-based applications.

Package builder provides build worker functionality including health checks.

Package builder provides build lifecycle test helpers and mock implementations.

Package builder provides build execution for Nix-based applications.

Package builder provides build job processing and recovery functionality.

Index

Constants

View Source
const (
	// ValidationCodeRequiredField indicates a required field is missing or empty.
	ValidationCodeRequiredField = "REQUIRED_FIELD"
	// ValidationCodeInvalidValue indicates a field has an invalid value.
	ValidationCodeInvalidValue = "INVALID_VALUE"
	// ValidationCodeNegativeValue indicates a field has a negative value when it should be non-negative.
	ValidationCodeNegativeValue = "NEGATIVE_VALUE"
)

Validation error codes. These codes are used to categorize validation errors for programmatic handling. **Validates: Requirements 3.4, 3.5, 3.6, 3.7, 3.8, 3.9**

View Source
const DefaultBuildTimeout = 1800

DefaultBuildTimeout is the default build timeout in seconds (30 minutes).

Variables

View Source
var (
	// ErrBuildTimeout is returned when a build exceeds its configured timeout.
	ErrBuildTimeout = errors.New("build exceeded timeout limit")
	// ErrValidationFailed is returned when build validation fails.
	ErrValidationFailed = errors.New("build validation failed")
	// ErrInvalidStateTransition is returned when an invalid state transition is attempted.
	ErrInvalidStateTransition = errors.New("invalid state transition")
)

Build timeout errors.

View Source
var ValidTransitions = models.ValidStatusTransitions

ValidTransitions is an alias to models.ValidStatusTransitions for backward compatibility in tests.

View Source
var WorkerVersion = "dev"

WorkerVersion is the current version of the worker. This should be set at build time using ldflags.

Functions

func CanTransition

func CanTransition(from, to models.BuildStatus, isRetry bool) bool

CanTransition delegates to models.CanTransition for state transition validation.

func GetBuildTimeout

func GetBuildTimeout(job *models.BuildJob, defaultTimeout int) time.Duration

GetBuildTimeout is an alias for GetEffectiveTimeout for backward compatibility. Deprecated: Use GetEffectiveTimeout instead.

func GetEffectiveTimeout

func GetEffectiveTimeout(job *models.BuildJob, defaultTimeout int) time.Duration

GetEffectiveTimeout returns the effective timeout for a build job. The timeout priority is: job.TimeoutSeconds > job.BuildConfig.BuildTimeout > defaultTimeout > DefaultBuildTimeout **Validates: Requirements 12.1, 12.2, 12.3**

func IsBuildTimeoutError

func IsBuildTimeoutError(err error) bool

IsBuildTimeoutError checks if an error is a build timeout error.

func IsCloneError

func IsCloneError(err error) bool

IsCloneError checks if an error is a CloneError.

func IsTerminalState

func IsTerminalState(status models.BuildStatus) bool

IsTerminalState delegates to models.IsTerminalState for terminal state checking.

func IsValidOCIImageTag

func IsValidOCIImageTag(tag string) bool

IsValidOCIImageTag checks if a string is a valid OCI image reference. Valid formats: registry/repo:tag or registry/repo@digest

func IsValidStorePath

func IsValidStorePath(path string) bool

IsValidStorePath checks if a string is a valid Nix store path.

func NewTestBuildJob

func NewTestBuildJob(id, deploymentID string, buildType models.BuildType, strategy models.BuildStrategy) *models.BuildJob

NewTestBuildJob creates a valid build job for testing.

func NewTestDeployment

func NewTestDeployment(id, appID string) *models.Deployment

NewTestDeployment creates a valid deployment for testing.

func StageDescription

func StageDescription(stage BuildStage) string

StageDescription returns a human-readable description of a build stage.

Types

type AtticClient

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

AtticClient provides methods for interacting with an Attic binary cache.

func NewAtticClient

func NewAtticClient(cfg *AtticConfig, logger *slog.Logger) *AtticClient

NewAtticClient creates a new Attic client.

func (*AtticClient) GetCacheInfo

func (c *AtticClient) GetCacheInfo(ctx context.Context) (*CacheInfo, error)

GetCacheInfo retrieves information about the Attic cache.

func (*AtticClient) Push

func (c *AtticClient) Push(ctx context.Context, storePath string) (*PushResult, error)

Push pushes a Nix store path (closure) to the Attic cache. It uses the attic CLI tool to push with cryptographic signatures.

func (*AtticClient) PushWithDependencies

func (c *AtticClient) PushWithDependencies(ctx context.Context, storePath string) (*PushResult, error)

PushWithDependencies pushes a store path and all its dependencies to Attic.

func (*AtticClient) SignClosure

func (c *AtticClient) SignClosure(ctx context.Context, storePath string) error

SignClosure signs a store path with the configured signing key. This is typically done automatically by Push, but can be called separately.

func (*AtticClient) Verify

func (c *AtticClient) Verify(ctx context.Context, storePath string) (bool, error)

Verify checks if a store path exists in the Attic cache.

type AtticConfig

type AtticConfig struct {
	Endpoint   string // Attic server endpoint (e.g., "https://cache.example.com")
	CacheName  string // Name of the cache to push to
	SigningKey string // Path to the signing key or the key itself
	Timeout    time.Duration
}

AtticConfig holds configuration for the Attic client.

func DefaultAtticConfig

func DefaultAtticConfig() *AtticConfig

DefaultAtticConfig returns an AtticConfig with sensible defaults.

type BuildJobFixtures

type BuildJobFixtures struct {
	// ValidPureNixFlake is a valid pure-nix build with flake strategy.
	ValidPureNixFlake *models.BuildJob
	// ValidOCIDockerfile is a valid OCI build with dockerfile strategy.
	ValidOCIDockerfile *models.BuildJob
	// ValidAutoGo is a valid auto-go build.
	ValidAutoGo *models.BuildJob
	// ValidAutoNode is a valid auto-node build.
	ValidAutoNode *models.BuildJob
	// ValidAutoRust is a valid auto-rust build.
	ValidAutoRust *models.BuildJob
	// ValidAutoPython is a valid auto-python build.
	ValidAutoPython *models.BuildJob
	// ValidNixpacks is a valid nixpacks build.
	ValidNixpacks *models.BuildJob
	// InvalidMissingID is a build job with missing ID.
	InvalidMissingID *models.BuildJob
	// InvalidMissingDeploymentID is a build job with missing deployment ID.
	InvalidMissingDeploymentID *models.BuildJob
	// InvalidBuildType is a build job with invalid build type.
	InvalidBuildType *models.BuildJob
	// InvalidStrategy is a build job with invalid strategy.
	InvalidStrategy *models.BuildJob
	// InvalidNegativeTimeout is a build job with negative timeout.
	InvalidNegativeTimeout *models.BuildJob
}

BuildJobFixtures provides pre-configured build jobs for testing.

func NewBuildJobFixtures

func NewBuildJobFixtures() *BuildJobFixtures

NewBuildJobFixtures creates a set of build job fixtures for testing.

type BuildProgressTracker

type BuildProgressTracker interface {
	// ReportStage reports current build stage.
	ReportStage(ctx context.Context, buildID string, stage BuildStage) error
	// ReportProgress reports percentage completion.
	ReportProgress(ctx context.Context, buildID string, percent int, message string) error
}

BuildProgressTracker reports build progress to users.

type BuildStage

type BuildStage string

BuildStage represents a phase in the build process.

const (
	StageCloning         BuildStage = "cloning"
	StageDetecting       BuildStage = "detecting"
	StageGenerating      BuildStage = "generating"
	StageCalculatingHash BuildStage = "calculating_hash"
	StageBuilding        BuildStage = "building"
	StagePushing         BuildStage = "pushing"
	StageCompleted       BuildStage = "completed"
	StageFailed          BuildStage = "failed"
)

type BuildValidator

type BuildValidator interface {
	// Validate checks if a build job configuration is valid.
	Validate(ctx context.Context, job *models.BuildJob) (*ValidationResult, error)
}

BuildValidator validates build configurations before execution.

type CacheInfo

type CacheInfo struct {
	Name           string   `json:"name"`
	IsPublic       bool     `json:"is_public"`
	StoreDir       string   `json:"store_dir"`
	Priority       int      `json:"priority"`
	UpstreamCaches []string `json:"upstream_caches,omitempty"`
}

CacheInfo holds information about an Attic cache.

type CloneError

type CloneError struct {
	// GitURL is the URL that was being cloned
	GitURL string

	// GitRef is the ref that was being checked out
	GitRef string

	// Stderr contains the git stderr output
	Stderr string

	// ExitCode is the exit code from git
	ExitCode int

	// Err is the underlying error
	Err error
}

CloneError represents a detailed error from a git clone operation.

func AsCloneError

func AsCloneError(err error) (*CloneError, bool)

AsCloneError attempts to convert an error to a CloneError.

func (*CloneError) Error

func (e *CloneError) Error() string

Error implements the error interface.

func (*CloneError) Unwrap

func (e *CloneError) Unwrap() error

Unwrap returns the underlying error.

type CloneResult

type CloneResult struct {
	// RepoPath is the path to the cloned repository
	RepoPath string

	// CommitSHA is the resolved commit SHA after checkout
	CommitSHA string
}

CloneResult contains the result of a successful clone operation.

func CloneRepository

func CloneRepository(ctx context.Context, gitURL, gitRef, destPath string) (*CloneResult, error)

CloneRepository clones a git repository to the specified destination path. It uses shallow clone (--depth 1) for efficiency as specified in Requirements 4.1.

Parameters:

  • ctx: Context for cancellation
  • gitURL: The git repository URL to clone
  • gitRef: The git ref to checkout (branch, tag, or commit). If empty, uses default branch.
  • destPath: The destination path for the cloned repository

Returns:

  • *CloneResult: Contains the repo path and resolved commit SHA
  • error: A *CloneError with detailed information on failure

**Validates: Requirements 1.1, 4.1**

type DefaultBuildValidator

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

DefaultBuildValidator is the default implementation of BuildValidator.

func NewDefaultBuildValidator

func NewDefaultBuildValidator(logger *slog.Logger) *DefaultBuildValidator

NewDefaultBuildValidator creates a new DefaultBuildValidator.

func (*DefaultBuildValidator) Validate

Validate checks if a build job configuration is valid. **Validates: Requirements 3.1, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9**

type DefaultProgressTracker

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

DefaultProgressTracker is a progress tracker that logs progress and maintains history. **Validates: Requirements 4.1, 4.2, 4.3**

func NewDefaultProgressTracker

func NewDefaultProgressTracker(logger *slog.Logger) *DefaultProgressTracker

NewDefaultProgressTracker creates a new DefaultProgressTracker.

func (*DefaultProgressTracker) ClearAllHistory

func (t *DefaultProgressTracker) ClearAllHistory()

ClearAllHistory clears all history (useful for testing).

func (*DefaultProgressTracker) ClearHistory

func (t *DefaultProgressTracker) ClearHistory(buildID string)

ClearHistory clears the history for a specific build (useful for testing).

func (*DefaultProgressTracker) GetLastStage

func (t *DefaultProgressTracker) GetLastStage(buildID string) (BuildStage, bool)

GetLastStage returns the last reported stage for a build.

func (*DefaultProgressTracker) GetProgressHistory

func (t *DefaultProgressTracker) GetProgressHistory(buildID string) []ProgressRecord

GetProgressHistory returns the progress history for a build. **Validates: Requirements 4.1, 4.2, 4.3**

func (*DefaultProgressTracker) GetStageHistory

func (t *DefaultProgressTracker) GetStageHistory(buildID string) []StageRecord

GetStageHistory returns the stage history for a build. **Validates: Requirements 4.1, 4.2**

func (*DefaultProgressTracker) HasTerminalStage

func (t *DefaultProgressTracker) HasTerminalStage(buildID string) bool

HasTerminalStage checks if the build has reported a terminal stage (completed or failed). **Validates: Requirements 4.5, 4.6**

func (*DefaultProgressTracker) IsProgressMonotonic

func (t *DefaultProgressTracker) IsProgressMonotonic(buildID string) bool

IsProgressMonotonic checks if all progress reports for a build are monotonically increasing. **Validates: Requirements 4.3**

func (*DefaultProgressTracker) ReportProgress

func (t *DefaultProgressTracker) ReportProgress(ctx context.Context, buildID string, percent int, message string) error

ReportProgress logs the build progress, validates monotonicity, and stores it in history. **Validates: Requirements 4.3** - Progress monotonicity validation

func (*DefaultProgressTracker) ReportStage

func (t *DefaultProgressTracker) ReportStage(ctx context.Context, buildID string, stage BuildStage) error

ReportStage logs the current build stage and stores it in history.

type HealthComponentStatus

type HealthComponentStatus struct {
	Status  HealthStatus `json:"status"`
	Message string       `json:"message,omitempty"`
}

HealthComponentStatus represents the health status of a single component.

type HealthResponse

type HealthResponse struct {
	Status     HealthStatus                     `json:"status"`
	Components map[string]HealthComponentStatus `json:"components"`
	Version    string                           `json:"version"`
	Uptime     string                           `json:"uptime"`
}

HealthResponse represents the health check response.

type HealthStatus

type HealthStatus string

HealthStatus represents the health status of a component.

const (
	// HealthStatusHealthy indicates the component is fully operational.
	HealthStatusHealthy HealthStatus = "healthy"
	// HealthStatusDegraded indicates the component is operational but with issues.
	HealthStatusDegraded HealthStatus = "degraded"
	// HealthStatusUnhealthy indicates the component is not operational.
	HealthStatusUnhealthy HealthStatus = "unhealthy"
)

type LifecycleMockLogStore

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

LifecycleMockLogStore is a mock implementation of LogStore for testing.

func NewLifecycleMockLogStore

func NewLifecycleMockLogStore() *LifecycleMockLogStore

NewLifecycleMockLogStore creates a new LifecycleMockLogStore.

func (*LifecycleMockLogStore) Create

func (m *LifecycleMockLogStore) Create(ctx context.Context, entry *models.LogEntry) error

func (*LifecycleMockLogStore) DeleteOlderThan

func (m *LifecycleMockLogStore) DeleteOlderThan(ctx context.Context, deploymentID string, before int64) error

func (*LifecycleMockLogStore) List

func (m *LifecycleMockLogStore) List(ctx context.Context, deploymentID string, limit int) ([]*models.LogEntry, error)

func (*LifecycleMockLogStore) ListBySource

func (m *LifecycleMockLogStore) ListBySource(ctx context.Context, deploymentID, source string, limit int) ([]*models.LogEntry, error)

type MockAppStore

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

MockAppStore is a mock implementation of AppStore for testing.

func NewMockAppStore

func NewMockAppStore() *MockAppStore

func (*MockAppStore) Create

func (m *MockAppStore) Create(ctx context.Context, app *models.App) error

func (*MockAppStore) Delete

func (m *MockAppStore) Delete(ctx context.Context, id string) error

func (*MockAppStore) Get

func (m *MockAppStore) Get(ctx context.Context, id string) (*models.App, error)

func (*MockAppStore) GetByName

func (m *MockAppStore) GetByName(ctx context.Context, ownerID, name string) (*models.App, error)

func (*MockAppStore) List

func (m *MockAppStore) List(ctx context.Context, ownerID string) ([]*models.App, error)

func (*MockAppStore) ListByOrg

func (m *MockAppStore) ListByOrg(ctx context.Context, orgID string) ([]*models.App, error)

func (*MockAppStore) Update

func (m *MockAppStore) Update(ctx context.Context, app *models.App) error

type MockAtticClient

type MockAtticClient struct {
	PushCalls     []MockPushCall
	PushResultVal *PushResult
	PushError     error
	ShouldFail    bool
	// contains filtered or unexported fields
}

MockAtticClient is a mock implementation of the AtticClient for testing.

func NewMockAtticClient

func NewMockAtticClient() *MockAtticClient

NewMockAtticClient creates a new MockAtticClient with default success behavior.

func (*MockAtticClient) GetPushCalls

func (m *MockAtticClient) GetPushCalls() []MockPushCall

GetPushCalls returns the recorded push calls.

func (*MockAtticClient) PushWithDependencies

func (m *MockAtticClient) PushWithDependencies(ctx context.Context, storePath string) (*PushResult, error)

PushWithDependencies implements the AtticClient interface.

func (*MockAtticClient) Reset

func (m *MockAtticClient) Reset()

Reset clears all recorded calls.

type MockBuildCall

type MockBuildCall struct {
	Job       *models.BuildJob
	Timestamp time.Time
}

MockBuildCall records a call to the mock builder.

type MockBuildStore

type MockBuildStore struct {

	// Track state transitions for verification
	StateTransitions []StateTransition
	// contains filtered or unexported fields
}

MockBuildStore is a mock implementation of BuildStore for testing.

func NewMockBuildStore

func NewMockBuildStore() *MockBuildStore

NewMockBuildStore creates a new MockBuildStore.

func (*MockBuildStore) Create

func (m *MockBuildStore) Create(ctx context.Context, build *models.BuildJob) error

func (*MockBuildStore) Get

func (*MockBuildStore) GetByDeployment

func (m *MockBuildStore) GetByDeployment(ctx context.Context, deploymentID string) (*models.BuildJob, error)

func (*MockBuildStore) GetStateTransitions

func (m *MockBuildStore) GetStateTransitions() []StateTransition

GetStateTransitions returns all recorded state transitions.

func (*MockBuildStore) List

func (m *MockBuildStore) List(ctx context.Context, appID string) ([]*models.BuildJob, error)

func (*MockBuildStore) ListByUser

func (m *MockBuildStore) ListByUser(ctx context.Context, userID string) ([]*models.BuildJob, error)

func (*MockBuildStore) ListPending

func (m *MockBuildStore) ListPending(ctx context.Context) ([]*models.BuildJob, error)

func (*MockBuildStore) ListQueued

func (m *MockBuildStore) ListQueued(ctx context.Context) ([]*models.BuildJob, error)

ListQueued retrieves all builds with status 'queued'. Used for startup recovery to resume pending builds. **Validates: Requirements 15.1**

func (*MockBuildStore) ListRunning

func (m *MockBuildStore) ListRunning(ctx context.Context) ([]*models.BuildJob, error)

ListRunning retrieves all builds with status 'running'. Used for startup recovery to identify interrupted builds. **Validates: Requirements 15.1, 15.2**

func (*MockBuildStore) Reset

func (m *MockBuildStore) Reset()

Reset clears all builds and transitions.

func (*MockBuildStore) Update

func (m *MockBuildStore) Update(ctx context.Context, build *models.BuildJob) error

type MockDeploymentStore

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

MockDeploymentStore is a mock implementation of DeploymentStore for testing.

func NewMockDeploymentStore

func NewMockDeploymentStore() *MockDeploymentStore

NewMockDeploymentStore creates a new MockDeploymentStore.

func (*MockDeploymentStore) CountByStatusAndOrg

func (m *MockDeploymentStore) CountByStatusAndOrg(ctx context.Context, status models.DeploymentStatus, orgID string) (int, error)

CountByStatusAndOrg counts deployments by status filtered by organization. Note: This mock implementation doesn't actually filter by org since it doesn't have access to app org_id.

func (*MockDeploymentStore) Create

func (m *MockDeploymentStore) Create(ctx context.Context, deployment *models.Deployment) error

func (*MockDeploymentStore) Get

func (*MockDeploymentStore) GetLatestSuccessful

func (m *MockDeploymentStore) GetLatestSuccessful(ctx context.Context, appID string) (*models.Deployment, error)

func (*MockDeploymentStore) GetNextVersion

func (m *MockDeploymentStore) GetNextVersion(ctx context.Context, appID, serviceName string) (int, error)

GetNextVersion returns the next version number for a service. Returns 1 for the first deployment, or max(version) + 1 for subsequent deployments.

func (*MockDeploymentStore) List

func (m *MockDeploymentStore) List(ctx context.Context, appID string) ([]*models.Deployment, error)

func (*MockDeploymentStore) ListByNode

func (m *MockDeploymentStore) ListByNode(ctx context.Context, nodeID string) ([]*models.Deployment, error)

func (*MockDeploymentStore) ListByStatus

func (m *MockDeploymentStore) ListByStatus(ctx context.Context, status models.DeploymentStatus) ([]*models.Deployment, error)

func (*MockDeploymentStore) ListByUser

func (m *MockDeploymentStore) ListByUser(ctx context.Context, userID string) ([]*models.Deployment, error)

func (*MockDeploymentStore) Reset

func (m *MockDeploymentStore) Reset()

Reset clears all deployments.

func (*MockDeploymentStore) Update

func (m *MockDeploymentStore) Update(ctx context.Context, deployment *models.Deployment) error

type MockDomainStore

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

MockDomainStore is a mock implementation of DomainStore for testing.

func NewMockDomainStore

func NewMockDomainStore() *MockDomainStore

func (*MockDomainStore) Create

func (m *MockDomainStore) Create(ctx context.Context, domain *models.Domain) error

func (*MockDomainStore) Delete

func (m *MockDomainStore) Delete(ctx context.Context, id string) error

func (*MockDomainStore) Get

func (m *MockDomainStore) Get(ctx context.Context, id string) (*models.Domain, error)

func (*MockDomainStore) GetByDomain

func (m *MockDomainStore) GetByDomain(ctx context.Context, domainName string) (*models.Domain, error)

func (*MockDomainStore) List

func (m *MockDomainStore) List(ctx context.Context, appID string) ([]*models.Domain, error)

func (*MockDomainStore) ListAll

func (m *MockDomainStore) ListAll(ctx context.Context) ([]*models.Domain, error)

type MockGitHubAccountStore

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

MockGitHubAccountStore is a mock implementation of GitHubAccountStore for testing.

func NewMockGitHubAccountStore

func NewMockGitHubAccountStore() *MockGitHubAccountStore

func (*MockGitHubAccountStore) Create

func (*MockGitHubAccountStore) Delete

func (m *MockGitHubAccountStore) Delete(ctx context.Context, id int64) error

func (*MockGitHubAccountStore) Get

func (*MockGitHubAccountStore) GetByUserID

func (m *MockGitHubAccountStore) GetByUserID(ctx context.Context, userID string) (*models.GitHubAccount, error)

func (*MockGitHubAccountStore) List

func (*MockGitHubAccountStore) Update

type MockGitHubStore

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

MockGitHubStore is a mock implementation of GitHubStore for testing.

func NewMockGitHubStore

func NewMockGitHubStore() *MockGitHubStore

func (*MockGitHubStore) CreateInstallation

func (m *MockGitHubStore) CreateInstallation(ctx context.Context, inst *models.GitHubInstallation) error

func (*MockGitHubStore) DeleteInstallation

func (m *MockGitHubStore) DeleteInstallation(ctx context.Context, id int64) error

func (*MockGitHubStore) GetConfig

func (*MockGitHubStore) GetInstallation

func (m *MockGitHubStore) GetInstallation(ctx context.Context, id int64) (*models.GitHubInstallation, error)

func (*MockGitHubStore) ListInstallations

func (m *MockGitHubStore) ListInstallations(ctx context.Context, userID string) ([]*models.GitHubInstallation, error)

func (*MockGitHubStore) ResetConfig

func (m *MockGitHubStore) ResetConfig(ctx context.Context) error

func (*MockGitHubStore) SaveConfig

func (m *MockGitHubStore) SaveConfig(ctx context.Context, config *models.GitHubAppConfig) error

type MockNixBuilder

type MockNixBuilder struct {
	BuildCalls   []MockBuildCall
	BuildResult  *executor.NixBuildResult
	BuildError   error
	BuildDelay   time.Duration
	ShouldFail   bool
	FailureError error
	// contains filtered or unexported fields
}

MockNixBuilder is a mock implementation of the NixBuilder interface for testing.

func NewMockNixBuilder

func NewMockNixBuilder() *MockNixBuilder

NewMockNixBuilder creates a new MockNixBuilder with default success behavior.

func (*MockNixBuilder) BuildWithLogCallback

func (m *MockNixBuilder) BuildWithLogCallback(ctx context.Context, job *models.BuildJob, callback func(line string)) (*executor.NixBuildResult, error)

BuildWithLogCallback implements the NixBuilder interface.

func (*MockNixBuilder) GetBuildCalls

func (m *MockNixBuilder) GetBuildCalls() []MockBuildCall

GetBuildCalls returns the recorded build calls.

func (*MockNixBuilder) Reset

func (m *MockNixBuilder) Reset()

Reset clears all recorded calls.

type MockNodeStore

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

MockNodeStore is a mock implementation of NodeStore for testing.

func NewMockNodeStore

func NewMockNodeStore() *MockNodeStore

func (*MockNodeStore) Get

func (m *MockNodeStore) Get(ctx context.Context, id string) (*models.Node, error)

func (*MockNodeStore) List

func (m *MockNodeStore) List(ctx context.Context) ([]*models.Node, error)

func (*MockNodeStore) ListHealthy

func (m *MockNodeStore) ListHealthy(ctx context.Context) ([]*models.Node, error)

func (*MockNodeStore) ListWithClosure

func (m *MockNodeStore) ListWithClosure(ctx context.Context, storePath string) ([]*models.Node, error)

func (*MockNodeStore) Register

func (m *MockNodeStore) Register(ctx context.Context, node *models.Node) error

func (*MockNodeStore) UpdateHealth

func (m *MockNodeStore) UpdateHealth(ctx context.Context, id string, healthy bool) error

func (*MockNodeStore) UpdateHeartbeat

func (m *MockNodeStore) UpdateHeartbeat(ctx context.Context, id string, resources *models.NodeResources) error

func (*MockNodeStore) UpdateHeartbeatWithDiskMetrics

func (m *MockNodeStore) UpdateHeartbeatWithDiskMetrics(ctx context.Context, id string, resources *models.NodeResources, diskMetrics *models.NodeDiskMetrics) error

type MockOCIBuilder

type MockOCIBuilder struct {
	BuildCalls   []MockBuildCall
	BuildResult  *executor.OCIBuildResult
	BuildError   error
	BuildDelay   time.Duration
	ShouldFail   bool
	FailureError error
	// contains filtered or unexported fields
}

MockOCIBuilder is a mock implementation of the OCIBuilder interface for testing.

func NewMockOCIBuilder

func NewMockOCIBuilder() *MockOCIBuilder

NewMockOCIBuilder creates a new MockOCIBuilder with default success behavior.

func (*MockOCIBuilder) BuildWithLogCallback

func (m *MockOCIBuilder) BuildWithLogCallback(ctx context.Context, job *models.BuildJob, callback func(line string)) (*executor.OCIBuildResult, error)

BuildWithLogCallback implements the OCIBuilder interface.

func (*MockOCIBuilder) GetBuildCalls

func (m *MockOCIBuilder) GetBuildCalls() []MockBuildCall

GetBuildCalls returns the recorded build calls.

func (*MockOCIBuilder) Reset

func (m *MockOCIBuilder) Reset()

Reset clears all recorded calls.

type MockOrgStore

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

MockOrgStore is a mock implementation of OrgStore for testing.

func NewMockOrgStore

func NewMockOrgStore() *MockOrgStore

NewMockOrgStore creates a new MockOrgStore.

func (*MockOrgStore) AddMember

func (m *MockOrgStore) AddMember(ctx context.Context, orgID, userID string, role models.Role) error

func (*MockOrgStore) Count

func (m *MockOrgStore) Count(ctx context.Context) (int, error)

func (*MockOrgStore) Create

func (m *MockOrgStore) Create(ctx context.Context, org *models.Organization) error

func (*MockOrgStore) Delete

func (m *MockOrgStore) Delete(ctx context.Context, id string) error

func (*MockOrgStore) Get

func (*MockOrgStore) GetBySlug

func (m *MockOrgStore) GetBySlug(ctx context.Context, slug string) (*models.Organization, error)

func (*MockOrgStore) GetDefault

func (m *MockOrgStore) GetDefault(ctx context.Context) (*models.Organization, error)

func (*MockOrgStore) GetDefaultForUser

func (m *MockOrgStore) GetDefaultForUser(ctx context.Context, userID string) (*models.Organization, error)

func (*MockOrgStore) IsMember

func (m *MockOrgStore) IsMember(ctx context.Context, orgID, userID string) (bool, error)

func (*MockOrgStore) List

func (m *MockOrgStore) List(ctx context.Context, userID string) ([]*models.Organization, error)

func (*MockOrgStore) ListMembers

func (m *MockOrgStore) ListMembers(ctx context.Context, orgID string) ([]*models.OrgMembership, error)

func (*MockOrgStore) RemoveMember

func (m *MockOrgStore) RemoveMember(ctx context.Context, orgID, userID string) error

func (*MockOrgStore) Update

func (m *MockOrgStore) Update(ctx context.Context, org *models.Organization) error

type MockProgressTracker

type MockProgressTracker struct {
	StageReports    []StageReport
	ProgressReports []ProgressReport
	// contains filtered or unexported fields
}

MockProgressTracker is a mock implementation of BuildProgressTracker for testing. It also implements ProgressTrackerWithHistory for testing progress tracking verification.

func NewMockProgressTracker

func NewMockProgressTracker() *MockProgressTracker

NewMockProgressTracker creates a new MockProgressTracker.

func (*MockProgressTracker) GetLastStage

func (m *MockProgressTracker) GetLastStage(buildID string) (BuildStage, bool)

GetLastStage returns the last reported stage for a build.

func (*MockProgressTracker) GetProgressHistory

func (m *MockProgressTracker) GetProgressHistory(buildID string) []ProgressRecord

GetProgressHistory returns the progress history for a build (implements ProgressTrackerWithHistory).

func (*MockProgressTracker) GetProgressReports

func (m *MockProgressTracker) GetProgressReports() []ProgressReport

GetProgressReports returns all recorded progress reports.

func (*MockProgressTracker) GetStageHistory

func (m *MockProgressTracker) GetStageHistory(buildID string) []StageRecord

GetStageHistory returns the stage history for a build (implements ProgressTrackerWithHistory).

func (*MockProgressTracker) GetStageReports

func (m *MockProgressTracker) GetStageReports() []StageReport

GetStageReports returns all recorded stage reports.

func (*MockProgressTracker) HasTerminalStage

func (m *MockProgressTracker) HasTerminalStage(buildID string) bool

HasTerminalStage checks if the build has reported a terminal stage (completed or failed).

func (*MockProgressTracker) IsProgressMonotonic

func (m *MockProgressTracker) IsProgressMonotonic(buildID string) bool

IsProgressMonotonic checks if all progress reports for a build are monotonically increasing.

func (*MockProgressTracker) ReportProgress

func (m *MockProgressTracker) ReportProgress(ctx context.Context, buildID string, percent int, message string) error

func (*MockProgressTracker) ReportStage

func (m *MockProgressTracker) ReportStage(ctx context.Context, buildID string, stage BuildStage) error

func (*MockProgressTracker) Reset

func (m *MockProgressTracker) Reset()

Reset clears all recorded reports.

type MockPushCall

type MockPushCall struct {
	StorePath string
	Timestamp time.Time
}

MockPushCall records a call to the mock Attic client.

type MockQueue

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

MockQueue is a mock implementation of Queue for testing.

func NewMockQueue

func NewMockQueue() *MockQueue

NewMockQueue creates a new MockQueue.

func (*MockQueue) Ack

func (m *MockQueue) Ack(ctx context.Context, jobID string) error

func (*MockQueue) Dequeue

func (m *MockQueue) Dequeue(ctx context.Context) (*models.BuildJob, error)

func (*MockQueue) Enqueue

func (m *MockQueue) Enqueue(ctx context.Context, job *models.BuildJob) error

func (*MockQueue) IsAcked

func (m *MockQueue) IsAcked(jobID string) bool

IsAcked returns true if the job was acknowledged.

func (*MockQueue) IsNacked

func (m *MockQueue) IsNacked(jobID string) bool

IsNacked returns true if the job was nacked.

func (*MockQueue) Nack

func (m *MockQueue) Nack(ctx context.Context, jobID string) error

func (*MockQueue) Reset

func (m *MockQueue) Reset()

Reset clears all queue state.

type MockSecretStore

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

MockSecretStore is a mock implementation of SecretStore for testing.

func NewMockSecretStore

func NewMockSecretStore() *MockSecretStore

func (*MockSecretStore) Delete

func (m *MockSecretStore) Delete(ctx context.Context, appID, key string) error

func (*MockSecretStore) Get

func (m *MockSecretStore) Get(ctx context.Context, appID, key string) ([]byte, error)

func (*MockSecretStore) GetAll

func (m *MockSecretStore) GetAll(ctx context.Context, appID string) (map[string][]byte, error)

func (*MockSecretStore) List

func (m *MockSecretStore) List(ctx context.Context, appID string) ([]string, error)

func (*MockSecretStore) Set

func (m *MockSecretStore) Set(ctx context.Context, appID, key string, encryptedValue []byte) error

type MockSettingsStore

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

MockSettingsStore is a mock implementation of SettingsStore for testing.

func NewMockSettingsStore

func NewMockSettingsStore() *MockSettingsStore

func (*MockSettingsStore) Get

func (m *MockSettingsStore) Get(ctx context.Context, key string) (string, error)

func (*MockSettingsStore) GetAll

func (m *MockSettingsStore) GetAll(ctx context.Context) (map[string]string, error)

func (*MockSettingsStore) Set

func (m *MockSettingsStore) Set(ctx context.Context, key, value string) error

type MockStore

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

MockStore is a mock implementation of the Store interface for testing.

func NewMockStore

func NewMockStore() *MockStore

NewMockStore creates a new MockStore.

func (*MockStore) Apps

func (m *MockStore) Apps() store.AppStore

func (*MockStore) Builds

func (m *MockStore) Builds() store.BuildStore

func (*MockStore) Close

func (m *MockStore) Close() error

func (*MockStore) Deployments

func (m *MockStore) Deployments() store.DeploymentStore

func (*MockStore) Domains

func (m *MockStore) Domains() store.DomainStore

func (*MockStore) GitHub

func (m *MockStore) GitHub() store.GitHubStore

func (*MockStore) GitHubAccounts

func (m *MockStore) GitHubAccounts() store.GitHubAccountStore

func (*MockStore) Invitations

func (m *MockStore) Invitations() store.InvitationStore

func (*MockStore) Logs

func (m *MockStore) Logs() store.LogStore

func (*MockStore) Nodes

func (m *MockStore) Nodes() store.NodeStore

func (*MockStore) Orgs

func (m *MockStore) Orgs() store.OrgStore

func (*MockStore) Ping

func (m *MockStore) Ping(ctx context.Context) error

func (*MockStore) Secrets

func (m *MockStore) Secrets() store.SecretStore

func (*MockStore) Settings

func (m *MockStore) Settings() store.SettingsStore

func (*MockStore) Users

func (m *MockStore) Users() store.UserStore

func (*MockStore) WithTx

func (m *MockStore) WithTx(ctx context.Context, fn func(store.Store) error) error

type MockUserStore

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

MockUserStore is a mock implementation of UserStore for testing.

func NewMockUserStore

func NewMockUserStore() *MockUserStore

func (*MockUserStore) Authenticate

func (m *MockUserStore) Authenticate(ctx context.Context, email, password string) (*store.User, error)

func (*MockUserStore) CountByRole

func (m *MockUserStore) CountByRole(ctx context.Context, role store.Role) (int, error)

func (*MockUserStore) Create

func (m *MockUserStore) Create(ctx context.Context, email, password string, isAdmin bool) (*store.User, error)

func (*MockUserStore) CreateWithRole

func (m *MockUserStore) CreateWithRole(ctx context.Context, email, password string, role store.Role, invitedBy string) (*store.User, error)

func (*MockUserStore) Delete

func (m *MockUserStore) Delete(ctx context.Context, id string) error

func (*MockUserStore) GetByEmail

func (m *MockUserStore) GetByEmail(ctx context.Context, email string) (*store.User, error)

func (*MockUserStore) GetByID

func (m *MockUserStore) GetByID(ctx context.Context, id string) (*store.User, error)

func (*MockUserStore) GetFirstOwner

func (m *MockUserStore) GetFirstOwner(ctx context.Context) (*store.User, error)

func (*MockUserStore) List

func (m *MockUserStore) List(ctx context.Context) ([]*store.User, error)

func (*MockUserStore) Update

func (m *MockUserStore) Update(ctx context.Context, user *store.User) error

type NixBuildResult

type NixBuildResult struct {
	StorePath string        // The Nix store path of the built derivation
	Logs      string        // Build logs
	Duration  time.Duration // Build duration
	ExitCode  int           // Exit code from the build
}

NixBuildResult holds the result of a Nix build.

type NixBuilder

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

NixBuilder executes Nix builds inside Podman containers.

func NewNixBuilder

func NewNixBuilder(cfg *NixBuilderConfig, logger *slog.Logger) (*NixBuilder, error)

NewNixBuilder creates a new NixBuilder instance.

func (*NixBuilder) Build

func (b *NixBuilder) Build(ctx context.Context, job *models.BuildJob) (*NixBuildResult, error)

Build executes a Nix build for the given job inside a Podman container. It clones the repository, runs nix build, and returns the store path.

func (*NixBuilder) BuildWithLogCallback

func (b *NixBuilder) BuildWithLogCallback(ctx context.Context, job *models.BuildJob, callback func(line string)) (*NixBuildResult, error)

BuildWithLogCallback executes a build and calls the callback for each log line. This is useful for streaming logs to a database in real-time.

type NixBuilderConfig

type NixBuilderConfig struct {
	WorkDir      string
	PodmanSocket string
	NixImage     string // Docker image with Nix installed
	AtticURL     string // Attic binary cache URL (e.g., "http://localhost:5000")
	AtticCache   string // Attic cache name (e.g., "narvana")
	AtticToken   string // Attic JWT token for authentication
}

NixBuilderConfig holds configuration for the Nix builder.

func DefaultNixBuilderConfig

func DefaultNixBuilderConfig() *NixBuilderConfig

DefaultNixBuilderConfig returns a NixBuilderConfig with sensible defaults.

type OCIBuildResult

type OCIBuildResult struct {
	ImageTag  string        // Full image tag (registry/repo:tag)
	StorePath string        // Nix store path of the image archive
	Logs      string        // Build logs
	Duration  time.Duration // Total build duration
	ExitCode  int           // Exit code from the build
}

OCIBuildResult holds the result of an OCI build.

type OCIBuilder

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

OCIBuilder builds OCI container images using Nix and pushes them to a registry.

func NewOCIBuilder

func NewOCIBuilder(cfg *OCIBuilderConfig, logger *slog.Logger) (*OCIBuilder, error)

NewOCIBuilder creates a new OCIBuilder instance.

func (*OCIBuilder) Build

func (b *OCIBuilder) Build(ctx context.Context, job *models.BuildJob) (*OCIBuildResult, error)

Build executes a Nix build that produces an OCI image and pushes it to the registry. The Nix flake should output a Docker image archive (via dockerTools.buildImage or similar).

func (*OCIBuilder) BuildWithLogCallback

func (b *OCIBuilder) BuildWithLogCallback(ctx context.Context, job *models.BuildJob, callback func(line string)) (*OCIBuildResult, error)

BuildWithLogCallback executes an OCI build and calls the callback for each log line.

type OCIBuilderConfig

type OCIBuilderConfig struct {
	NixBuilderConfig *NixBuilderConfig
	Registry         string // Registry URL (e.g., "localhost:5000" or "registry.example.com")
	RegistryAuth     string // Base64 encoded auth string for registry
	PodmanSocket     string
}

OCIBuilderConfig holds configuration for the OCI builder.

func DefaultOCIBuilderConfig

func DefaultOCIBuilderConfig() *OCIBuilderConfig

DefaultOCIBuilderConfig returns an OCIBuilderConfig with sensible defaults.

type ProgressRecord

type ProgressRecord struct {
	BuildID   string
	Percent   int
	Message   string
	Timestamp time.Time
}

ProgressRecord tracks a single progress report for verification. **Validates: Requirements 4.1, 4.2, 4.3**

type ProgressReport

type ProgressReport struct {
	BuildID   string
	Percent   int
	Message   string
	Timestamp time.Time
}

ProgressReport records a progress report.

type ProgressTrackerWithHistory

type ProgressTrackerWithHistory interface {
	BuildProgressTracker
	// GetProgressHistory returns the progress history for a build.
	GetProgressHistory(buildID string) []ProgressRecord
	// GetStageHistory returns the stage history for a build.
	GetStageHistory(buildID string) []StageRecord
}

ProgressTrackerWithHistory extends BuildProgressTracker with history retrieval. **Validates: Requirements 4.1, 4.2, 4.3**

type PushResult

type PushResult struct {
	StorePath string        // The store path that was pushed
	CacheURL  string        // URL where the closure can be fetched
	Duration  time.Duration // Time taken to push
}

PushResult holds the result of pushing a closure to Attic.

type RecoveryResult

type RecoveryResult struct {
	// InterruptedBuilds is the number of builds marked as failed due to interruption.
	InterruptedBuilds int
	// ResumedBuilds is the number of builds re-queued for processing.
	ResumedBuilds int
	// Errors contains any errors encountered during recovery.
	Errors []error
}

RecoveryResult contains the results of a startup recovery operation.

type RecoveryService

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

RecoveryService handles startup recovery for pending and interrupted builds. It ensures that builds survive API restarts by: 1. Marking interrupted builds (status = "running") as failed 2. Re-queuing pending builds from the builds table **Validates: Requirements 15.1, 15.2**

func NewRecoveryService

func NewRecoveryService(s store.Store, q queue.Queue, logger *slog.Logger) *RecoveryService

NewRecoveryService creates a new RecoveryService.

func (*RecoveryService) RecoverOnStartup

func (r *RecoveryService) RecoverOnStartup(ctx context.Context) (*RecoveryResult, error)

RecoverOnStartup performs startup recovery for builds. This should be called when the API server or worker starts. **Validates: Requirements 15.1, 15.2**

type SchedulerInterface

type SchedulerInterface interface {
	ScheduleAndAssign(ctx context.Context, deployment *models.Deployment) error
}

Worker processes build jobs from the queue. SchedulerInterface defines the scheduling operations needed by the worker.

type StageRecord

type StageRecord struct {
	BuildID   string
	Stage     BuildStage
	Timestamp time.Time
}

StageRecord tracks a single stage report for verification. **Validates: Requirements 4.1, 4.2**

type StageReport

type StageReport struct {
	BuildID   string
	Stage     BuildStage
	Timestamp time.Time
}

StageReport records a stage report.

type StateTransition

type StateTransition struct {
	BuildID   string
	FromState models.BuildStatus
	ToState   models.BuildStatus
	Timestamp time.Time
}

StateTransition records a state change for a build job.

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
	Code    string `json:"code"`
}

ValidationError describes a validation failure.

func (ValidationError) Error

func (e ValidationError) Error() string

Error implements the error interface.

type ValidationResult

type ValidationResult struct {
	Valid    bool              `json:"valid"`
	Errors   []ValidationError `json:"errors,omitempty"`
	Warnings []string          `json:"warnings,omitempty"`
}

ValidationResult contains validation results.

func ValidateBuildJob

func ValidateBuildJob(ctx context.Context, job *models.BuildJob) (*ValidationResult, error)

ValidateBuildJob validates a build job and returns any validation errors. This is a convenience function for external callers.

type Worker

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

func NewWorker

func NewWorker(cfg *WorkerConfig, s store.Store, q queue.Queue, logger *slog.Logger) (*Worker, error)

NewWorker creates a new build worker.

func (*Worker) GetProgressTracker

func (w *Worker) GetProgressTracker() BuildProgressTracker

GetProgressTracker returns the current progress tracker.

func (*Worker) ProcessSingleJob

func (w *Worker) ProcessSingleJob(ctx context.Context, job *models.BuildJob) error

ProcessSingleJob processes a single job without the worker loop. This is useful for testing or one-off builds.

func (*Worker) SetProgressTracker

func (w *Worker) SetProgressTracker(tracker BuildProgressTracker)

SetProgressTracker sets a custom progress tracker for the worker. This is useful for integrating with external progress reporting systems.

func (*Worker) SetScheduler

func (w *Worker) SetScheduler(s SchedulerInterface)

Start begins processing build jobs from the queue. It spawns multiple goroutines based on the configured concurrency. SetScheduler sets the scheduler for the worker to use after builds complete.

func (*Worker) Start

func (w *Worker) Start(ctx context.Context) error

func (*Worker) Stop

func (w *Worker) Stop()

Stop gracefully stops the worker and waits for all jobs to complete.

type WorkerConfig

type WorkerConfig struct {
	Concurrency    int
	NixConfig      *NixBuilderConfig
	OCIConfig      *OCIBuilderConfig
	AtticConfig    *AtticConfig
	DefaultTimeout int // Default build timeout in seconds (default: 1800 = 30 minutes)
}

WorkerConfig holds configuration for the build worker.

func DefaultWorkerConfig

func DefaultWorkerConfig() *WorkerConfig

DefaultWorkerConfig returns a WorkerConfig with sensible defaults.

type WorkerHealthChecker

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

WorkerHealthChecker performs health checks for the worker.

func NewWorkerHealthChecker

func NewWorkerHealthChecker(db *sql.DB, version string) *WorkerHealthChecker

NewWorkerHealthChecker creates a new worker health checker.

func (*WorkerHealthChecker) Check

Check performs all health checks and returns the aggregated response.

func (*WorkerHealthChecker) Handler

func (c *WorkerHealthChecker) Handler() http.HandlerFunc

Handler returns an HTTP handler for health checks.

func (*WorkerHealthChecker) SetTimeout

func (c *WorkerHealthChecker) SetTimeout(timeout time.Duration)

SetTimeout sets the timeout for health checks.

Directories

Path Synopsis
Package buildtype provides build type selection logic for different build strategies.
Package buildtype provides build type selection logic for different build strategies.
Package cache provides build caching for faster rebuilds.
Package cache provides build caching for faster rebuilds.
Package clone provides git repository cloning utilities for the build system.
Package clone provides git repository cloning utilities for the build system.
Package detector provides build strategy detection for repositories.
Package detector provides build strategy detection for repositories.
Package entrypoint provides entry point selection for multi-binary projects.
Package entrypoint provides entry point selection for multi-binary projects.
Package errors provides enhanced error handling for the build system.
Package errors provides enhanced error handling for the build system.
Package executor provides strategy-specific build execution.
Package executor provides strategy-specific build execution.
Package flakelock provides flake.lock file management for reproducible builds.
Package flakelock provides flake.lock file management for reproducible builds.
Package hash provides vendor hash calculation for reproducible builds.
Package hash provides vendor hash calculation for reproducible builds.
Package metrics provides build performance tracking and metrics collection.
Package metrics provides build performance tracking and metrics collection.
Package retry provides build retry management functionality.
Package retry provides build retry management functionality.
Package templates provides Nix flake template rendering for build strategies.
Package templates provides Nix flake template rendering for build strategies.
databases
Package databases provides database flake template registry and configuration.
Package databases provides database flake template registry and configuration.

Jump to

Keyboard shortcuts

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