Documentation
¶
Overview ¶
Package models provides data structures for the Narvana platform.
Package models provides data structures for the Narvana platform.
Package models provides data models for the Narvana platform.
Index ¶
- Variables
- func CanTransition(from, to BuildStatus, isRetry bool) bool
- func GenerateContainerName(appName, serviceName string, version int) string
- func GenerateSlug(name string) string
- func GetCurrentSystem() string
- func IsNixStorePath(path string) bool
- func IsOCIImageTag(tag string) bool
- func IsTerminalState(status BuildStatus) bool
- type App
- type ArtifactType
- type BuildConfig
- type BuildJob
- type BuildResult
- type BuildStatus
- type BuildStrategy
- type BuildType
- type DatabaseConfig
- type DatabaseOptions
- type Deployment
- type DeploymentStatus
- type DetectionResult
- type DiskStats
- type DjangoOptions
- type Domain
- type FastAPIOptions
- type Framework
- type GitHubAccount
- type GitHubAppConfig
- type GitHubInstallation
- type GitHubRepository
- type HealthCheckConfig
- type Invitation
- type InvitationStatus
- type LogEntry
- type NextJSOptions
- type Node
- type NodeDiskMetrics
- type NodeResources
- type OrgMembership
- type Organization
- type PortMapping
- type ResourceSpec
- type Role
- type RuntimeConfig
- type Secret
- type ServiceAction
- type ServiceConfig
- type ServiceState
- type SourceType
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ( ErrOrgNameRequired = errors.New("organization name is required") ErrOrgNameTooLong = errors.New("organization name must be 63 characters or less") ErrOrgSlugRequired = errors.New("organization slug is required") ErrOrgSlugTooLong = errors.New("organization slug must be 63 characters or less") ErrOrgSlugInvalid = errors.New("organization slug must contain only lowercase letters, numbers, and hyphens") ErrOrgSlugStartEnd = errors.New("organization slug must start and end with a letter or number") ErrLastOrgDelete = errors.New("cannot delete the last organization") )
Validation errors for organizations.
var ValidStatusTransitions = map[BuildStatus][]BuildStatus{ BuildStatusQueued: {BuildStatusRunning}, BuildStatusRunning: {BuildStatusSucceeded, BuildStatusFailed, BuildStatusQueued}, BuildStatusSucceeded: {}, BuildStatusFailed: {}, }
ValidStatusTransitions defines the allowed state transitions for build jobs. The state machine is: queued → running → (succeeded | failed) with running → queued only allowed for retry operations.
Functions ¶
func CanTransition ¶
func CanTransition(from, to BuildStatus, isRetry bool) bool
CanTransition checks if a state transition is valid. The isRetry parameter indicates if this is a retry operation, which allows the special case of running → queued transition.
func GenerateContainerName ¶
GenerateContainerName creates a unique container name with version. Format: {appName}-{serviceName}-v{version} **Validates: Requirements 9.3, 9.4, 9.5**
func GenerateSlug ¶
GenerateSlug generates a URL-friendly slug from the organization name.
func GetCurrentSystem ¶
func GetCurrentSystem() string
GetCurrentSystem returns the Nix system string for the current platform.
func IsNixStorePath ¶
IsNixStorePath checks if a string is a valid Nix store path. Nix store paths follow the format: /nix/store/<hash>-<name> **Validates: Requirements 13.1**
func IsOCIImageTag ¶
IsOCIImageTag checks if a string is a valid OCI image tag. OCI image tags follow formats like: - registry.example.com/image:tag - registry.example.com/namespace/image:tag - image:tag - image@sha256:digest **Validates: Requirements 13.2**
func IsTerminalState ¶
func IsTerminalState(status BuildStatus) bool
IsTerminalState returns true if the status is a terminal state (succeeded or failed). Terminal states do not allow any further transitions.
Types ¶
type App ¶
type App struct {
ID string `json:"id"`
OrgID string `json:"org_id"` // Organization ID for multi-tenancy
OwnerID string `json:"owner_id"` // User who created the app
Name string `json:"name"`
Description string `json:"description,omitempty"`
IconURL string `json:"icon_url,omitempty"`
Services []ServiceConfig `json:"services"`
Version int `json:"version"` // Version for optimistic locking
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at,omitempty"`
}
App represents a user-defined deployable unit that may contain one or more services.
type ArtifactType ¶
type ArtifactType string
ArtifactType represents the type of build artifact produced.
const ( // ArtifactTypeStorePath represents a Nix store path artifact (for pure-nix builds). ArtifactTypeStorePath ArtifactType = "store_path" // ArtifactTypeImageTag represents an OCI image tag artifact (for OCI builds). ArtifactTypeImageTag ArtifactType = "image_tag" // ArtifactTypeUnknown represents an unknown or invalid artifact type. ArtifactTypeUnknown ArtifactType = "unknown" )
func GetExpectedArtifactType ¶
func GetExpectedArtifactType(buildType BuildType) ArtifactType
GetExpectedArtifactType returns the expected artifact type for a build type. **Validates: Requirements 13.1, 13.2**
func ValidateArtifact ¶
func ValidateArtifact(buildType BuildType, artifact string) (ArtifactType, bool)
ValidateArtifact validates that an artifact is appropriate for the given build type. For pure-nix builds, the artifact should be a Nix store path. For OCI builds, the artifact should be an image tag. **Validates: Requirements 13.1, 13.2**
type BuildConfig ¶
type BuildConfig struct {
// Common options
BuildCommand string `json:"build_command,omitempty"`
StartCommand string `json:"start_command,omitempty"`
EntryPoint string `json:"entry_point,omitempty"`
BuildTimeout int `json:"build_timeout,omitempty"` // seconds, default 1800
// Go-specific
GoVersion string `json:"go_version,omitempty"`
CGOEnabled *bool `json:"cgo_enabled,omitempty"` // Explicit CGO control (nil = auto-detect) **Validates: Requirements 16.5**
// Go build tags (e.g., ["integration", "debug"]) **Validates: Requirements 17.1**
BuildTags []string `json:"build_tags,omitempty"`
// Custom ldflags for Go linker (e.g., "-X main.version=1.0.0") **Validates: Requirements 18.1**
Ldflags string `json:"ldflags,omitempty"`
// Pre/post build hooks **Validates: Requirements 21.1, 21.2**
PreBuildCommands []string `json:"pre_build_commands,omitempty"` // Commands to run before build
PostBuildCommands []string `json:"post_build_commands,omitempty"` // Commands to run after build
// Go workspace support **Validates: Requirements 22.1, 22.2, 22.3, 22.4**
IsWorkspace bool `json:"is_workspace,omitempty"` // True if go.work file detected
WorkspaceModule string `json:"workspace_module,omitempty"` // Selected module to build in workspace
// Node.js-specific
NodeVersion string `json:"node_version,omitempty"`
PackageManager string `json:"package_manager,omitempty"` // npm, yarn, pnpm
// Rust-specific
RustEdition string `json:"rust_edition,omitempty"`
// Python-specific
PythonVersion string `json:"python_version,omitempty"`
// Framework-specific options
NextJSOptions *NextJSOptions `json:"nextjs_options,omitempty"`
DjangoOptions *DjangoOptions `json:"django_options,omitempty"`
FastAPIOptions *FastAPIOptions `json:"fastapi_options,omitempty"`
DatabaseOptions *DatabaseOptions `json:"database_options,omitempty"`
// Advanced options
ExtraNixPackages []string `json:"extra_nix_packages,omitempty"`
EnvironmentVars map[string]string `json:"environment_vars,omitempty"`
// Fallback behavior
AutoRetryAsOCI bool `json:"auto_retry_as_oci,omitempty"`
}
BuildConfig contains strategy-specific configuration options.
type BuildJob ¶
type BuildJob struct {
ID string `json:"id"`
DeploymentID string `json:"deployment_id"`
AppID string `json:"app_id"`
ServiceName string `json:"service_name,omitempty"`
// Source information - explicit fields for clarity
// SourceType indicates whether this is a git, flake, or database source
// For git sources: GitURL contains the original git URL, FlakeURI contains the constructed flake URI
// For flake sources: FlakeURI contains the direct flake URI, GitURL is empty
// For database sources: Both GitURL and FlakeURI may be empty
SourceType SourceType `json:"source_type,omitempty" db:"source_type"`
GitURL string `json:"git_url"`
GitRef string `json:"git_ref"`
FlakeURI string `json:"flake_uri,omitempty" db:"flake_uri"` // Constructed or direct flake URI
FlakeOutput string `json:"flake_output"`
BuildType BuildType `json:"build_type"`
Status BuildStatus `json:"status"`
CreatedAt time.Time `json:"created_at"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
// Build strategy fields
BuildStrategy BuildStrategy `json:"build_strategy,omitempty" db:"build_strategy"`
BuildConfig *BuildConfig `json:"build_config,omitempty" db:"build_config"`
GeneratedFlake string `json:"generated_flake,omitempty" db:"generated_flake"`
FlakeLock string `json:"flake_lock,omitempty" db:"flake_lock"`
VendorHash string `json:"vendor_hash,omitempty" db:"vendor_hash"`
// Resource limits and retry tracking
TimeoutSeconds int `json:"timeout_seconds,omitempty" db:"timeout_seconds"`
RetryCount int `json:"retry_count,omitempty" db:"retry_count"`
RetryAsOCI bool `json:"retry_as_oci,omitempty" db:"retry_as_oci"`
// Detection results from pre-build phase
// **Validates: Requirements 2.1**
DetectionResult *DetectionResult `json:"detection_result,omitempty" db:"detection_result"`
DetectedAt *time.Time `json:"detected_at,omitempty" db:"detected_at"`
// PreClonedRepoPath is the path to a pre-cloned repository from the pre-build phase.
// When set, the build container will mount this path instead of cloning the repository.
// **Validates: Requirements 4.2**
PreClonedRepoPath string `json:"pre_cloned_repo_path,omitempty" db:"-"`
}
BuildJob represents a build task in the queue.
func (*BuildJob) ValidateBuildJobSource ¶
ValidateBuildJobSource validates that the BuildJob source fields are consistent. For git sources: GitURL must be non-empty, FlakeURI should contain the constructed flake URI For flake sources: FlakeURI must be non-empty, GitURL should be empty **Validates: Requirements 27.1, 27.2, 27.3**
type BuildResult ¶
type BuildResult struct {
Artifact string `json:"artifact"`
StorePath string `json:"store_path,omitempty"` // For pure-nix
ImageTag string `json:"image_tag,omitempty"` // For OCI
Logs string `json:"logs"`
}
BuildResult represents the output of a completed build.
type BuildStatus ¶
type BuildStatus string
BuildStatus represents the current state of a build job.
const ( BuildStatusQueued BuildStatus = "queued" BuildStatusRunning BuildStatus = "running" BuildStatusSucceeded BuildStatus = "succeeded" BuildStatusFailed BuildStatus = "failed" )
type BuildStrategy ¶
type BuildStrategy string
BuildStrategy represents the method used to build an application.
const ( BuildStrategyFlake BuildStrategy = "flake" // Use existing flake.nix BuildStrategyAutoGo BuildStrategy = "auto-go" // Generate flake for Go BuildStrategyAutoRust BuildStrategy = "auto-rust" // Generate flake for Rust BuildStrategyAutoNode BuildStrategy = "auto-node" // Generate flake for Node.js BuildStrategyAutoPython BuildStrategy = "auto-python" // Generate flake for Python BuildStrategyAutoDatabase BuildStrategy = "auto-database" // Generate flake for databases BuildStrategyDockerfile BuildStrategy = "dockerfile" // Build from Dockerfile BuildStrategyNixpacks BuildStrategy = "nixpacks" // Use Nixpacks BuildStrategyAuto BuildStrategy = "auto" // Auto-detect )
func ValidBuildStrategies ¶
func ValidBuildStrategies() []BuildStrategy
ValidBuildStrategies returns all valid build strategy options.
func (BuildStrategy) IsValid ¶
func (s BuildStrategy) IsValid() bool
IsValid checks if the build strategy is a valid option.
type BuildType ¶
type BuildType string
BuildType represents the deployment mode for an application.
func EnforceBuildType ¶
func EnforceBuildType(strategy BuildStrategy, requestedType BuildType) (BuildType, bool)
EnforceBuildType ensures the correct build type for a strategy. Some strategies (dockerfile, nixpacks) require OCI build type. Returns the enforced build type and whether it was changed from the requested type. **Validates: Requirements 10.2, 11.2, 18.1, 18.2**
type DatabaseConfig ¶
type DatabaseConfig struct {
Type string `json:"type"` // e.g., "sqlite", "postgres"
Version string `json:"version"` // e.g., "3", "16"
}
DatabaseConfig defines settings for internal database services.
type DatabaseOptions ¶
type DatabaseOptions struct {
Type string `json:"type,omitempty"`
Version string `json:"version,omitempty"`
}
DatabaseOptions contains database-specific build options.
type Deployment ¶
type Deployment struct {
ID string `json:"id"`
AppID string `json:"app_id"`
ServiceName string `json:"service_name"`
Version int `json:"version"`
GitRef string `json:"git_ref"`
GitCommit string `json:"git_commit,omitempty"`
BuildType BuildType `json:"build_type"`
Artifact string `json:"artifact,omitempty"`
Status DeploymentStatus `json:"status"`
NodeID string `json:"node_id,omitempty"`
Resources *ResourceSpec `json:"resources,omitempty"`
Config *RuntimeConfig `json:"config,omitempty"`
DependsOn []string `json:"depends_on,omitempty"` // Service names this deployment depends on
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
Deployment represents an instance of an application version running on one or more nodes.
func (*Deployment) ContainerName ¶
func (d *Deployment) ContainerName() string
ContainerName returns the container name for this deployment. It uses the app name from the deployment's app ID (first 8 chars) and service name. For a proper app name, use GenerateContainerName with the actual app name.
type DeploymentStatus ¶
type DeploymentStatus string
DeploymentStatus represents the current state of a deployment.
const ( DeploymentStatusPending DeploymentStatus = "pending" DeploymentStatusBuilding DeploymentStatus = "building" DeploymentStatusBuilt DeploymentStatus = "built" DeploymentStatusScheduled DeploymentStatus = "scheduled" DeploymentStatusStarting DeploymentStatus = "starting" DeploymentStatusRunning DeploymentStatus = "running" DeploymentStatusStopping DeploymentStatus = "stopping" DeploymentStatusStopped DeploymentStatus = "stopped" DeploymentStatusFailed DeploymentStatus = "failed" )
type DetectionResult ¶
type DetectionResult struct {
Strategy BuildStrategy `json:"strategy"`
Framework Framework `json:"framework"`
Version string `json:"version"`
SuggestedConfig map[string]interface{} `json:"suggested_config,omitempty"`
RecommendedBuildType BuildType `json:"recommended_build_type"`
EntryPoints []string `json:"entry_points,omitempty"`
Confidence float64 `json:"confidence"`
Warnings []string `json:"warnings,omitempty"`
}
DetectionResult contains the results of analyzing a repository.
type DiskStats ¶
type DiskStats struct {
Path string `json:"path"`
Total int64 `json:"total"`
Used int64 `json:"used"`
Available int64 `json:"available"`
UsagePercent float64 `json:"usage_percent"`
}
DiskStats represents disk usage statistics for a specific path. **Validates: Requirements 20.1**
type DjangoOptions ¶
type DjangoOptions struct {
SettingsModule string `json:"settings_module,omitempty"` // e.g., "myapp.settings"
StaticRoot string `json:"static_root,omitempty"` // Static files directory
CollectStatic bool `json:"collect_static,omitempty"` // Run collectstatic
Migrations bool `json:"migrations,omitempty"` // Run migrations on deploy
}
DjangoOptions contains Django-specific build options.
type Domain ¶
type Domain struct {
ID string `json:"id"`
AppID string `json:"app_id"`
Service string `json:"service"`
Domain string `json:"domain"`
IsWildcard bool `json:"is_wildcard"`
Verified bool `json:"verified"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Domain represents a custom domain mapping for a service.
type FastAPIOptions ¶
type FastAPIOptions struct {
AppModule string `json:"app_module,omitempty"` // e.g., "main:app"
Workers int `json:"workers,omitempty"` // Uvicorn workers
}
FastAPIOptions contains FastAPI-specific build options.
type Framework ¶
type Framework string
Framework represents a detected application framework.
const ( FrameworkGeneric Framework = "generic" FrameworkNextJS Framework = "nextjs" FrameworkExpress Framework = "express" FrameworkReact Framework = "react" FrameworkFastify Framework = "fastify" FrameworkDjango Framework = "django" FrameworkFastAPI Framework = "fastapi" FrameworkFlask Framework = "flask" )
type GitHubAccount ¶
type GitHubAccount struct {
ID int64 `json:"id" db:"id"`
Login string `json:"login" db:"login"`
Name string `json:"name" db:"name"`
Email string `json:"email" db:"email"`
AvatarURL string `json:"avatar_url" db:"avatar_url"`
AccessToken string `json:"-" db:"access_token"`
RefreshToken string `json:"-" db:"refresh_token"`
Expiry time.Time `json:"-" db:"expiry"`
TokenType string `json:"-" db:"token_type"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
UserID string `json:"user_id" db:"user_id"`
}
GitHubAccount represents a user's GitHub account connected via OAuth.
type GitHubAppConfig ¶
type GitHubAppConfig struct {
ID string `json:"id" db:"id"`
ConfigType string `json:"config_type" db:"config_type"` // "app" or "oauth"
AppID *int64 `json:"app_id" db:"app_id"` // Nullable
ClientID string `json:"client_id" db:"client_id"`
ClientSecret string `json:"client_secret" db:"client_secret"`
WebhookSecret *string `json:"webhook_secret,omitempty" db:"webhook_secret"` // Nullable
PrivateKey *string `json:"-" db:"private_key"` // Nullable
Slug *string `json:"slug" db:"slug"` // Nullable
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
GitHubAppConfig stores the credentials for a GitHub App or OAuth App.
type GitHubInstallation ¶
type GitHubInstallation struct {
ID int64 `json:"id" db:"id"`
AccountID int64 `json:"account_id" db:"account_id"`
AccountLogin string `json:"account_login" db:"account_login"`
AccountType string `json:"account_type" db:"account_type"` // "User" or "Organization"
AccessTokensURL string `json:"access_tokens_url" db:"access_tokens_url"`
RepositoriesURL string `json:"repositories_url" db:"repositories_url"`
HTMLURL string `json:"html_url" db:"html_url"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
UserID string `json:"user_id" db:"user_id"`
}
GitHubInstallation represents an installation of the GitHub App.
type GitHubRepository ¶
type GitHubRepository struct {
ID int64 `json:"id"`
Name string `json:"name"`
FullName string `json:"full_name"`
HTMLURL string `json:"html_url"`
Private bool `json:"private"`
Description string `json:"description"`
DefaultBranch string `json:"default_branch"`
}
GitHubRepository represents a repository returned by the GitHub API.
type HealthCheckConfig ¶
type HealthCheckConfig struct {
Path string `json:"path,omitempty"`
Port int `json:"port,omitempty"`
IntervalSeconds int `json:"interval_seconds,omitempty"`
TimeoutSeconds int `json:"timeout_seconds,omitempty"`
Retries int `json:"retries,omitempty"`
}
HealthCheckConfig defines health check settings for a service.
type Invitation ¶
type Invitation struct {
ID string `json:"id"`
Email string `json:"email"`
Token string `json:"token"` // Unique token for accepting the invitation
InvitedBy string `json:"invited_by"`
Role Role `json:"role"`
Status InvitationStatus `json:"status"`
ExpiresAt time.Time `json:"expires_at"`
AcceptedAt *time.Time `json:"accepted_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
Invitation represents an invitation to join the platform.
func (*Invitation) IsExpired ¶
func (i *Invitation) IsExpired() bool
IsExpired returns true if the invitation has expired.
func (*Invitation) IsValid ¶
func (i *Invitation) IsValid() bool
IsValid returns true if the invitation can be accepted.
type InvitationStatus ¶
type InvitationStatus string
InvitationStatus represents the status of an invitation.
const ( // InvitationStatusPending indicates the invitation has not been accepted. InvitationStatusPending InvitationStatus = "pending" // InvitationStatusAccepted indicates the invitation has been accepted. InvitationStatusAccepted InvitationStatus = "accepted" // InvitationStatusExpired indicates the invitation has expired. InvitationStatusExpired InvitationStatus = "expired" // InvitationStatusRevoked indicates the invitation was revoked. InvitationStatusRevoked InvitationStatus = "revoked" )
type LogEntry ¶
type LogEntry struct {
ID string `json:"id"`
DeploymentID string `json:"deployment_id"`
Source string `json:"source"` // "build" or "runtime"
Level string `json:"level"`
Message string `json:"message"`
Timestamp time.Time `json:"timestamp"`
}
LogEntry represents a single log entry from a build or runtime.
type NextJSOptions ¶
type NextJSOptions struct {
OutputMode string `json:"output_mode,omitempty"` // "standalone", "export", "default"
BasePath string `json:"base_path,omitempty"` // Base path for deployment
AssetPrefix string `json:"asset_prefix,omitempty"` // CDN prefix for assets
ImageOptimizer bool `json:"image_optimizer,omitempty"` // Enable image optimization
}
NextJSOptions contains Next.js-specific build options.
type Node ¶
type Node struct {
ID string `json:"id"`
Hostname string `json:"hostname"`
Address string `json:"address"`
GRPCPort int `json:"grpc_port"`
Healthy bool `json:"healthy"`
Resources *NodeResources `json:"resources"`
DiskMetrics *NodeDiskMetrics `json:"disk_metrics,omitempty"`
CachedPaths []string `json:"cached_paths,omitempty"`
LastHeartbeat time.Time `json:"last_heartbeat"`
RegisteredAt time.Time `json:"registered_at"`
}
Node represents a compute instance running the Narvana node agent, Podman, and Caddy.
type NodeDiskMetrics ¶
type NodeDiskMetrics struct {
NixStore *DiskStats `json:"nix_store,omitempty"`
ContainerStorage *DiskStats `json:"container_storage,omitempty"`
}
NodeDiskMetrics contains disk usage metrics for specific paths on a node. **Validates: Requirements 20.1**
type NodeResources ¶
type NodeResources struct {
CPUTotal float64 `json:"cpu_total"`
CPUAvailable float64 `json:"cpu_available"`
MemoryTotal int64 `json:"memory_total"`
MemoryAvailable int64 `json:"memory_available"`
DiskTotal int64 `json:"disk_total"`
DiskAvailable int64 `json:"disk_available"`
}
NodeResources represents the resource availability of a node.
type OrgMembership ¶
type OrgMembership struct {
OrgID string `json:"org_id"`
UserID string `json:"user_id"`
Role Role `json:"role"` // owner or member
CreatedAt time.Time `json:"created_at"`
}
OrgMembership links users to organizations with roles.
type Organization ¶
type Organization struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"` // URL-friendly identifier
Description string `json:"description,omitempty"`
IconURL string `json:"icon_url,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Organization represents a top-level grouping for all resources.
func (*Organization) Validate ¶
func (o *Organization) Validate() error
Validate validates the organization fields.
func (*Organization) ValidateName ¶
func (o *Organization) ValidateName() error
ValidateName validates the organization name.
func (*Organization) ValidateSlug ¶
func (o *Organization) ValidateSlug() error
ValidateSlug validates the organization slug.
type PortMapping ¶
type PortMapping struct {
ContainerPort int `json:"container_port"`
Protocol string `json:"protocol,omitempty"` // tcp or udp, defaults to tcp
}
PortMapping defines a port mapping for a service.
type ResourceSpec ¶
type ResourceSpec struct {
CPU string `json:"cpu"` // CPU allocation, e.g., "0.5", "1", "2"
Memory string `json:"memory"` // Memory allocation, e.g., "256Mi", "1Gi"
}
ResourceSpec defines direct CPU and memory resource allocation.
func DefaultResourceSpec ¶
func DefaultResourceSpec() *ResourceSpec
DefaultResourceSpec returns the default resource specification. These defaults are used when no resources are specified.
type RuntimeConfig ¶
type RuntimeConfig struct {
Resources *ResourceSpec `json:"resources,omitempty"`
EnvVars map[string]string `json:"env_vars,omitempty"`
Ports []PortMapping `json:"ports,omitempty"`
HealthCheck *HealthCheckConfig `json:"health_check,omitempty"`
}
RuntimeConfig holds runtime configuration for a deployment.
type Secret ¶
type Secret struct {
ID string `json:"id"`
AppID string `json:"app_id"`
Key string `json:"key"`
EncryptedValue []byte `json:"-"` // Excluded from JSON serialization
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Secret represents an encrypted secret associated with an application.
type ServiceAction ¶
type ServiceAction string
ServiceAction represents an action that can be performed on a service.
const ( // ServiceActionDeploy triggers a new deployment. ServiceActionDeploy ServiceAction = "deploy" // ServiceActionStop gracefully stops the service container. ServiceActionStop ServiceAction = "stop" // ServiceActionReload restarts the service without rebuilding. ServiceActionReload ServiceAction = "reload" // ServiceActionRebuild triggers a full rebuild and deployment. ServiceActionRebuild ServiceAction = "rebuild" // ServiceActionStart starts a stopped service. ServiceActionStart ServiceAction = "start" // ServiceActionRetry retries a failed deployment. ServiceActionRetry ServiceAction = "retry" )
type ServiceConfig ¶
type ServiceConfig struct {
Name string `json:"name"`
// Source configuration (exactly one must be set)
SourceType SourceType `json:"source_type"`
// Git source (SourceTypeGit)
// Decomposed fields that build worker combines into flake URI
GitRepo string `json:"git_repo,omitempty"` // e.g., "github.com/company/web-ui"
GitRef string `json:"git_ref,omitempty"` // Branch/tag/commit (default: "main")
FlakeOutput string `json:"flake_output,omitempty"` // Output path (default: "packages.${system}.default")
// Flake source (SourceTypeFlake)
// Complete flake URI used as-is by build worker
FlakeURI string `json:"flake_uri,omitempty"` // e.g., "github:owner/repo#packages.x86_64-linux.api"
// Image source (SourceTypeImage)
// OCI image reference, build phase skipped
Image string `json:"image,omitempty"` // e.g., "docker.io/postgres:16"
// Database source (SourceTypeDatabase)
Database *DatabaseConfig `json:"database,omitempty"`
// Build strategy configuration
BuildStrategy BuildStrategy `json:"build_strategy,omitempty" db:"build_strategy"`
BuildConfig *BuildConfig `json:"build_config,omitempty" db:"build_config"`
// Runtime configuration
Resources *ResourceSpec `json:"resources,omitempty"` // CPU/memory specification
Replicas int `json:"replicas"`
Ports []PortMapping `json:"ports,omitempty"`
HealthCheck *HealthCheckConfig `json:"health_check,omitempty"`
EnvVars map[string]string `json:"env_vars,omitempty"` // Service-level env vars (override app-level)
DependsOn []string `json:"depends_on,omitempty"`
}
ServiceConfig defines a single runnable component within an application.
func ParseServiceConfigJSON ¶
func ParseServiceConfigJSON(data []byte) (*ServiceConfig, error)
ParseServiceConfigJSON parses a JSON byte slice into a ServiceConfig, applies defaults, and validates the result. This is the recommended way to deserialize a ServiceConfig from JSON.
func (*ServiceConfig) ApplyDefaults ¶
func (s *ServiceConfig) ApplyDefaults()
ApplyDefaults applies default values to a ServiceConfig after deserialization. This ensures consistent behavior when optional fields are not specified. It does NOT modify user-specified values.
func (*ServiceConfig) BuildFlakeURI ¶
func (s *ServiceConfig) BuildFlakeURI() string
BuildFlakeURI constructs a flake URI for git sources. For git sources, this combines git_repo, git_ref, and flake_output. For flake sources, this returns the flake_uri directly.
func (*ServiceConfig) Clone ¶
func (s *ServiceConfig) Clone() ServiceConfig
Clone creates a deep copy of the ServiceConfig. This is useful for preserving the original configuration before modifications.
func (*ServiceConfig) Equals ¶
func (s *ServiceConfig) Equals(other *ServiceConfig) bool
Equals compares two ServiceConfig instances for equality. This is used for round-trip testing to verify serialization consistency.
func (*ServiceConfig) Validate ¶
func (s *ServiceConfig) Validate() error
Validate validates the service configuration.
func (*ServiceConfig) ValidateAndApplyDefaults ¶
func (s *ServiceConfig) ValidateAndApplyDefaults() error
ValidateAndApplyDefaults validates the ServiceConfig and applies defaults. This is the recommended way to process a ServiceConfig after deserialization. It first validates the configuration, then applies defaults for any missing optional fields. Returns an error if validation fails.
type ServiceState ¶
type ServiceState string
ServiceState represents the current operational state of a service. This is derived from the latest deployment status for the service.
const ( // ServiceStateNew indicates the service has never been deployed. ServiceStateNew ServiceState = "new" // ServiceStateDeploying indicates a deployment is in progress. ServiceStateDeploying ServiceState = "deploying" // ServiceStateRunning indicates the service container is running. ServiceStateRunning ServiceState = "running" // ServiceStateStopped indicates the service was manually stopped. ServiceStateStopped ServiceState = "stopped" // ServiceStateFailed indicates the last deployment failed. ServiceStateFailed ServiceState = "failed" )
func DeriveServiceState ¶
func DeriveServiceState(latestDeployment *Deployment) ServiceState
DeriveServiceState derives the service state from the latest deployment status. If there are no deployments, the service is in the "new" state.
func ValidServiceStates ¶
func ValidServiceStates() []ServiceState
ValidServiceStates returns all valid service states.
func (ServiceState) AvailableActions ¶
func (s ServiceState) AvailableActions() []ServiceAction
AvailableActions returns the actions available for a service in this state. **Feature: platform-enhancements, Property 2: Service State Action Availability** **Validates: Requirements 7.1, 7.2, 7.3, 7.4, 7.5, 7.6**
func (ServiceState) HasAction ¶
func (s ServiceState) HasAction(action ServiceAction) bool
HasAction returns true if the given action is available for this state.
func (ServiceState) IsValid ¶
func (s ServiceState) IsValid() bool
IsValid returns true if the service state is a valid state.
func (ServiceState) String ¶
func (s ServiceState) String() string
String returns the string representation of the service state.
type SourceType ¶
type SourceType string
SourceType represents the type of source for a service.
const ( SourceTypeGit SourceType = "git" // Git repo built via Nix flake SourceTypeFlake SourceType = "flake" // Direct flake URI (e.g., nixpkgs#redis) SourceTypeImage SourceType = "image" // Pre-built OCI image SourceTypeDatabase SourceType = "database" // Internal database (SQLite, etc.) )
type ValidationError ¶
ValidationError represents a service configuration validation error.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string