types

package
v0.0.1-dev.137 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package types defines the core data structures for the Rune orchestration platform.

Package types contains the canonical data model used across the Rune control plane and CLI. ClusterNetwork lives here so both the allocator (server side) and the CLI (rune admin network status) can share a single struct without an import cycle.

Package types: ingress / expose validation.

ValidateExpose enforces the pre-cast invariants required by the ingress controller:

  • acme TLS requires a non-empty Host (the ACME provider needs a hostname to issue against).
  • Path, when set, must start with "/".

This is a value-shape check; it does not require any cluster state and is safe to call from cast pipelines and admission tests.

Package types: ingress certificate state.

IngressCertStatus tracks the per-host TLS certificate lifecycle for services exposed via the ingress controller (RUNE-066). Certificate issuance is asynchronous: cast admits the service immediately, and the ACME orchestrator drives the state machine independently, updating IngressCertStatus as it makes progress.

Package types: well-known node and resource labels.

These constants are the single source of truth for label keys the networking layer reads (RUNE-066 ingress controller, future scheduling tickets). Keep them in sync with the operator-facing docs.

Package types — Snapshot resource (skeleton; full impl in RUNE-071).

The shape lives here so the storage Driver interface (RUNE-069) can refer to *types.Snapshot in Snapshot/RestoreFromSnapshot. RUNE-071 fills in the controller, gRPC service, and CLI; the resource itself is stable.

Package types — StorageClass resource definitions.

Introduced in RUNE-073.

Package types — Volume resource definitions for the storage subsystem.

Introduced in RUNE-069.

Index

Constants

View Source
const (
	AlertStateOK      = "ok"
	AlertStatePending = "pending"
	AlertStateFiring  = "firing"
)

Alert states (the evaluator's state machine).

View Source
const (
	ChannelTypeWebhook = "webhook"
	ChannelTypeSlack   = "slack"
)

Channel types.

View Source
const (
	InitStepReasonImageUnreachable = "ImageUnreachable"
	InitStepReasonNonZeroExit      = "NonZeroExit"
	InitStepReasonTimeout          = "Timeout"
	InitStepReasonRuntimeError     = "RuntimeError"
)

InitStepReason is a short, machine-friendly slug rolled up by the instance controller when an InitStep terminates non-Succeeded.

View Source
const (
	// LabelNodeRole identifies the operational role of a node.
	// The ingress controller (RUNE-066) runs only on nodes whose
	// role contains "edge". Multiple roles are comma-separated.
	LabelNodeRole = "rune.io/role"

	// NodeRoleEdge marks an edge node — one that owns :80/:443
	// and terminates external ingress (HTTP/HTTPS, ACME).
	NodeRoleEdge = "edge"
)

Well-known node labels.

View Source
const (
	ImagePullAlways  = "always"
	ImagePullMissing = "missing"
	ImagePullNever   = "never"
)

ImagePull values for Service.ImagePull.

View Source
const (
	ExposeTLSModeManual = "manual"
	ExposeTLSModeACME   = "acme"
	// ExposeTLSModeAuto is a user-friendly synonym for ExposeTLSModeACME.
	// Both "auto" and "acme" request a Let's Encrypt-issued certificate.
	ExposeTLSModeAuto = "auto"
)

Well-known TLS modes for ExposeServiceTLS.Mode.

View Source
const (
	ServiceReasonImageUnreachable = "ImageUnreachable" // image can't be pulled (auth, missing tag, network)
	ServiceReasonUnhealthy        = "Unhealthy"        // liveness/readiness probe failing
	ServiceReasonRestarting       = "Restarting"       // instance keeps exiting and being restarted
	ServiceReasonOutOfMemory      = "OutOfMemory"      // killed for exceeding the memory limit
	ServiceReasonUnplaceable      = "Unplaceable"      // no node has the capacity / matches placement
	ServiceReasonConfigMissing    = "ConfigMissing"    // referenced secret/configmap/env not found
	ServiceReasonLaunchFailed     = "LaunchFailed"     // runner refused to start the instance
	ServiceReasonExited           = "Exited"           // instance ran to completion (non-zero or otherwise)
	ServiceReasonUnknown          = "Unknown"          // no recognisable signal
)

Well-known StatusReason values for Service.StatusReason. The reconciler derives one of these from the worst-instance state. Keep this set small and stable — operators may script against it.

These names are intentionally Rune-shaped (verbs and plain English), not borrowed from Kubernetes' Pod conditions.

View Source
const (
	// TopologyLabelRegion identifies a coarse-grained placement region
	// ("nyc3", "us-east-1", "hetzner-fsn1"). Set by operators on each node.
	TopologyLabelRegion = "rune.io/region"

	// TopologyLabelZone identifies a fine-grained availability zone
	// ("us-east-1a"). Required for AWS EBS / GCP PD topology constraints.
	TopologyLabelZone = "rune.io/zone"

	// TopologyLabelHostPathRoot identifies the host path root prefix that a
	// node has provisioned for local-host volumes ("/mnt/rune"). Used as
	// implicit affinity for the local-host driver.
	TopologyLabelHostPathRoot = "rune.io/host-path-root"
)

Well-known topology label keys reserved by the storage subsystem. Drivers and StorageClass.AllowedTopologies should use these keys.

View Source
const (
	ClientCertModeRequire = "require"
)

Well-known ExposeClientCert.Mode values.

View Source
const ClusterNetworkName = "cluster"

ClusterNetworkName is the canonical name of the singleton ClusterNetwork resource.

View Source
const (
	// DefaultNamespace is the default namespace for services.
	DefaultNamespace = "default"
)
View Source
const ManagerRuneset = "runeset"

ManagerRuneset is the OwnedBy.Manager value for runeset-managed resources.

View Source
const RestoreFromSnapshotParam = "rune.io/restoreFromSnapshot"

RestoreFromSnapshotParam is the well-known Volume.Parameters key the SnapshotService stamps on a restore-target Volume so the VolumeController routes its first reconcile through Driver.RestoreFromSnapshot instead of Driver.Provision.

Format: "<snapshot-namespace>/<snapshot-name>".

View Source
const ServiceReasonInitStepFailed = "InitStepFailed"

ServiceReasonInitStepFailed is the Service.StatusReason value surfaced when any init step on any instance terminates Failed.

Variables

This section is empty.

Functions

func DeriveServiceReason

func DeriveServiceReason(status InstanceStatus, message string) string

DeriveServiceReason inspects an instance's status and message and returns a short, stable Service.StatusReason slug. Used by the reconciler to roll up an unhealthy instance into a service-level reason that's friendly to display in tables and to script against.

func DetectDependencyCycles

func DetectDependencyCycles(adj map[string][]string) []error

DetectDependencyCycles runs cycle detection on an adjacency list of service dependency edges. The adjacency list maps node keys ("ns/name") to a slice of neighbor node keys. It returns one error per cycle detected with a human-readable path; returns empty slice if no cycles.

func FormatCPU

func FormatCPU(cpu float64) string

FormatCPU formats a CPU value as a string Examples: 0.1 -> "100m", 0.5 -> "500m", 2.0 -> "2"

func FormatIDRef

func FormatIDRef(rt ResourceType, ns, id string) string

func FormatMemory

func FormatMemory(bytes int64) string

FormatMemory formats memory bytes as a human-readable string Uses binary units (Ki, Mi, Gi, etc.)

func FormatRef

func FormatRef(rt ResourceType, ns, name string) string

func HasNodeRole

func HasNodeRole(labels map[string]string, role string) bool

HasNodeRole reports whether labels carry the given role under LabelNodeRole. Empty role or labels return false. Comparison is case-sensitive and exact (no substring match) so that "edge-staging" does not match "edge".

func IsCastFile

func IsCastFile(filename string) (bool, error)

IsCastFile performs a lightweight detection to determine if a YAML file appears to define Rune resource specs (services, secrets, configmaps). It does not validate structure; it only checks for presence of known keys.

func IsEdgeNode

func IsEdgeNode(labels map[string]string) bool

IsEdgeNode is shorthand for HasNodeRole(labels, NodeRoleEdge).

func IsRuneConfigFile

func IsRuneConfigFile(filePath string) (bool, error)

IsRuneConfigFile checks if a file appears to be a Rune configuration file. Accepts either YAML or TOML (TOML is detected by the `.toml` extension and transcoded to YAML internally so we can reuse the same AST-based key-counting heuristic).

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if an error is a ValidationError.

func MakeDependencyNodeKey

func MakeDependencyNodeKey(namespace, name string) string

MakeDependencyNodeKey constructs a stable key for a service node as "namespace/name".

func MarshalSecretPayload

func MarshalSecretPayload(s *Secret) ([]byte, error)

MarshalSecretPayload serializes a secret INCLUDING Data for trusted transport (the release Cast payload path). Secret.Data is json:"-" so it never leaks through ordinary API marshaling — but a rendered cast payload must carry the values to the server, or every cast secret arrives empty. UnmarshalSecretPayload is the symmetric decode.

func NS

func NS(namespace string) string

NS returns the namespace, defaulting to DefaultNamespace if empty

func ParseCPU

func ParseCPU(cpu string) (float64, error)

ParseCPU parses a CPU request/limit string into a float64 (cores) Examples: "100m" -> 0.1, "0.5" -> 0.5, "2" -> 2.0

func ParseMemory

func ParseMemory(memory string) (int64, error)

ParseMemory parses a memory request/limit string into bytes Examples: "100Mi" -> 104857600, "1Gi" -> 1073741824, "2G" -> 2000000000

func ValidateExpose

func ValidateExpose(e *ServiceExpose, onEdge bool) error

ValidateExpose checks a ServiceExpose value for the invariants required by the ingress controller. Returns nil if e is nil.

onEdge is reserved for future per-edge checks (currently unused; kept in the signature for API stability).

func ValidateMountPathConflicts

func ValidateMountPathConflicts(owner string, scale int, vols []VolumeMount, secs []SecretMount, cfgs []ConfigmapMount) error

ValidateMountPathConflicts enforces cast-time invariants that span multiple mount kinds on a single Service spec. All checks are statically evaluable — no store or driver lookups required.

Rules enforced:

  • No two mounts (volume + secret + configmap) may share a mountPath.
  • No mountPath may sit inside (or equal) any path in systemMountBlocklist (/proc, /sys, /dev, container-runtime sockets).
  • When a service is RWO-attached and Scale > 1, the controller cannot bind the same volume to N replicas; flag the spec at cast-time.

The owner argument is a free-form label ("service foo", "job bar") included in error messages.

func ValidateProcessRuntimeVolumes

func ValidateProcessRuntimeVolumes(owner string, runtime RuntimeType, vols []VolumeMount) error

ValidateProcessRuntimeVolumes flags claimTemplate mounts on process-runtime services that target a StorageClass other than the local host-path classes. This is a static cast-time check intended to catch obvious misuse early — it does NOT cover Claim references to pre-existing volumes (those require a store lookup and are validated at bind time).

The owner argument is a free-form label included in error messages.

func ValidateVolumeMounts

func ValidateVolumeMounts(mounts []VolumeMount) error

ValidateVolumeMounts checks per-mount invariants that can be evaluated statically from the spec alone (no store / driver lookups). Used by both Service.Validate and ServiceSpec.Validate so the same rules fire from the API server's CreateService path and from `rune cast` / `rune lint`.

Rules enforced:

  • mount.Name and mount.MountPath are required.
  • MountPath is absolute and not "/".
  • SubPath, when set, is relative and contains no ".." segments.
  • Exactly one of Claim / ClaimTemplate is set.
  • Claim.Name is non-empty.
  • ClaimTemplate.Size is non-empty and parses with ParseMemory.
  • ClaimTemplate.AccessMode is required and a known constant.
  • ClaimTemplate.ReclaimPolicy, if set, is a known constant.
  • Mount.Name and MountPath are unique within the slice.

func WrapValidationError

func WrapValidationError(err error, format string, args ...interface{}) error

WrapValidationError wraps an error with additional context.

Types

type ACMEConfig

type ACMEConfig struct {
	Directory string `yaml:"directory,omitempty"`
	Email     string `yaml:"email,omitempty"`
}

ACMEConfig holds the Let's Encrypt directory + contact email used by the edge ingress (RUNE-067).

type AccessMode

type AccessMode string

AccessMode describes how a Volume may be mounted by attached instances.

const (
	// AccessModeRWO allows read/write by a single instance at a time.
	AccessModeRWO AccessMode = "ReadWriteOnce"
	// AccessModeROX allows read-only mount by many instances simultaneously.
	AccessModeROX AccessMode = "ReadOnlyMany"
	// AccessModeRWX allows read/write by many instances simultaneously.
	// Only honoured by drivers whose Capabilities advertise it (NFS, etc.).
	AccessModeRWX AccessMode = "ReadWriteMany"
)

type AlertRule

type AlertRule struct {
	// Unique identifier.
	ID string `json:"id" yaml:"id"`

	// DNS-1123 cluster-unique name.
	Name string `json:"name" yaml:"name"`

	// Description is optional free text shown in the rules table.
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// LogQL is the log selector + line filters whose matching lines are
	// counted (e.g. `{service="payments", level="error"} |= "boom"`). It must
	// be a plain log query — the alerter adds the count_over_time aggregation
	// itself. Validated at save time.
	LogQL string `json:"logql" yaml:"logql"`

	// Window is the rolling count window (the `[5m]` part).
	Window time.Duration `json:"window" yaml:"window"`

	// Op compares the windowed count to Threshold: ">", ">=", "<", "<=",
	// "==". Absence/heartbeat alerts are `== 0` (or `< 1`).
	Op string `json:"op" yaml:"op"`

	// Threshold is the count compared against.
	Threshold float64 `json:"threshold" yaml:"threshold"`

	// For is how long the condition must hold before pending becomes firing
	// (the hysteresis that stops one noisy evaluation from paging). Zero
	// fires on the first true evaluation.
	For time.Duration `json:"for,omitempty" yaml:"for,omitempty"`

	// Interval is the evaluation cadence. Zero uses the alerter default (60s).
	Interval time.Duration `json:"interval,omitempty" yaml:"interval,omitempty"`

	// Channels are the Channel names notified on firing and resolved
	// transitions. Alert state changes always also emit a Rune event.
	Channels []string `json:"channels,omitempty" yaml:"channels,omitempty"`

	// Disabled pauses evaluation without deleting the rule. (Inverted so the
	// zero value means enabled.)
	Disabled bool `json:"disabled,omitempty" yaml:"disabled,omitempty"`

	// CreatedBy attributes the rule (auth principal name; informational).
	CreatedBy string `json:"createdBy,omitempty" yaml:"createdBy,omitempty"`

	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

AlertRule is a RuneSight log-based alert: a LogQL log selector evaluated as a count over a rolling window, compared against a threshold. Rules are cluster-scoped, evaluated by the runed alerter loop, and fire through channels (see Channel). The Core-tier shape — count thresholds and absence (`== 0`) — works identically on every log backend, embedded included.

type AuditEvent

type AuditEvent struct {
	// ID is a unique identifier for the event; ulid-or-uuid string.
	ID string `json:"id" yaml:"id"`

	// Timestamp is when the event was emitted (server clock).
	Timestamp time.Time `json:"timestamp" yaml:"timestamp"`

	// Actor is the authenticated subject ID, or "anonymous" if no auth was
	// established (e.g., bootstrap path) or "unknown" if we could not extract
	// a subject from the request context.
	Actor string `json:"actor" yaml:"actor"`

	// Action is the verb performed (create, update, delete, get, reveal, ...).
	Action string `json:"action" yaml:"action"`

	// Resource is the resource type (e.g., "secrets", "configmaps").
	Resource string `json:"resource" yaml:"resource"`

	// ResourceRef is the canonical "<namespace>/<name>" reference of the
	// affected object, when applicable. Empty for namespace-less actions.
	ResourceRef string `json:"resourceRef,omitempty" yaml:"resourceRef,omitempty"`

	// Namespace is the namespace of the resource (denormalized from ResourceRef
	// for cheap filtering).
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

	// Outcome reports whether the operation succeeded.
	Outcome AuditOutcome `json:"outcome" yaml:"outcome"`

	// Message is an optional human-readable note (failure reason, etc.).
	// MUST NOT contain plaintext secret payloads.
	Message string `json:"message,omitempty" yaml:"message,omitempty"`

	// Metadata is a free-form bag for non-sensitive context (e.g., key set
	// hash, version number, previous version on rollback).
	Metadata map[string]string `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}

AuditEvent records a single security-relevant operation. It is append-only and intended to provide a queryable trail separate from the structured application log. Stored as a regular store resource under the system namespace.

type AuditOutcome

type AuditOutcome string

AuditOutcome captures whether the audited operation succeeded or was denied.

const (
	AuditOutcomeSuccess AuditOutcome = "success"
	AuditOutcomeDenied  AuditOutcome = "denied"
	AuditOutcomeError   AuditOutcome = "error"
)

type AuthConfig

type AuthConfig struct {
	APIKeys          string `yaml:"api_keys,omitempty"`
	Provider         string `yaml:"provider,omitempty"`
	Token            string `yaml:"token,omitempty"`
	AllowRemoteAdmin bool   `yaml:"allow_remote_admin,omitempty"`
}

AuthConfig represents authentication configuration

type CORSPolicy

type CORSPolicy struct {
	// Allowed origins (e.g., "https://example.com")
	AllowOrigins []string `json:"allowOrigins" yaml:"allowOrigins"`

	// Allowed methods (e.g., "GET", "POST")
	AllowMethods []string `json:"allowMethods,omitempty" yaml:"allowMethods,omitempty"`

	// Allowed headers
	AllowHeaders []string `json:"allowHeaders,omitempty" yaml:"allowHeaders,omitempty"`

	// Exposed headers
	ExposeHeaders []string `json:"exposeHeaders,omitempty" yaml:"exposeHeaders,omitempty"`

	// Max age for CORS preflight requests in seconds
	MaxAge int `json:"maxAge,omitempty" yaml:"maxAge,omitempty"`

	// Allow credentials
	AllowCredentials bool `json:"allowCredentials,omitempty" yaml:"allowCredentials,omitempty"`
}

CORSPolicy defines Cross-Origin Resource Sharing settings.

type CPUConfig

type CPUConfig struct {
	DefaultRequest string `yaml:"default_request,omitempty"`
	DefaultLimit   string `yaml:"default_limit,omitempty"`
}

CPUConfig represents CPU resource configuration

type CastFile

type CastFile struct {
	Specs          []Spec          `yaml:"specs,omitempty"`
	Services       []ServiceSpec   `yaml:"services,omitempty"`
	Secrets        []SecretSpec    `yaml:"secrets,omitempty"`
	Configmaps     []ConfigmapSpec `yaml:"configmaps,omitempty"`
	StorageClasses []StorageClass  `yaml:"storageClasses,omitempty"`
	Volumes        []Volume        `yaml:"volumes,omitempty"`
	// contains filtered or unexported fields
}

CastFile represents a YAML file that may contain multiple resource specifications.

func ParseCastFile

func ParseCastFile(filename string, overrideNamespace string) (*CastFile, error)

ParseCastFile reads and parses a cast file, handling template syntax

func ParseCastFileFromBytes

func ParseCastFileFromBytes(data []byte, overrideNamespace string) (*CastFile, error)

ParseCastFileFromBytes is a helper used in tests to parse cast YAML content from memory.

func (*CastFile) AddParseError

func (cf *CastFile) AddParseError(err error)

AddParseError adds a parsing error to the collection

func (*CastFile) GetConfigmapSpecs

func (cf *CastFile) GetConfigmapSpecs() []*ConfigmapSpec

GetConfigmapSpecs returns all configmap specs defined in the cast file.

func (*CastFile) GetConfigmaps

func (cf *CastFile) GetConfigmaps() ([]*Configmap, error)

GetConfigmaps converts inline configmap entries to concrete Configmap objects.

func (*CastFile) GetLineInfo

func (cf *CastFile) GetLineInfo(kind, namespace, name string) (int, bool)

GetLineInfo returns the approximate line number for a spec by kind/namespace/name

func (*CastFile) GetParseErrors

func (cf *CastFile) GetParseErrors() []error

GetParseErrors returns all parsing errors collected during file parsing

func (*CastFile) GetSecretSpecs

func (cf *CastFile) GetSecretSpecs() []*SecretSpec

GetSecretSpecs returns all secret specs defined in the cast file.

func (*CastFile) GetSecrets

func (cf *CastFile) GetSecrets() ([]*Secret, error)

GetSecrets converts inline secret entries to concrete Secret objects.

func (*CastFile) GetServiceSpecs

func (cf *CastFile) GetServiceSpecs() []*ServiceSpec

GetServices returns all service specs defined in the cast file.

func (*CastFile) GetServices

func (cf *CastFile) GetServices() ([]*Service, error)

GetServices converts service specs to concrete Service objects.

func (*CastFile) GetSpecs

func (cf *CastFile) GetSpecs() []Spec

GetSpecs returns all specs defined in the cast file.

func (*CastFile) GetStorageClasses

func (cf *CastFile) GetStorageClasses() ([]*StorageClass, error)

GetStorageClasses returns concrete StorageClass objects parsed from the cast file. StorageClasses are cluster-scoped (no namespace).

func (*CastFile) GetTemplateMap

func (cf *CastFile) GetTemplateMap() map[string]string

GetTemplateMap returns the map of template placeholders to their original template references

func (*CastFile) GetVolumes

func (cf *CastFile) GetVolumes() ([]*Volume, error)

GetVolumes returns concrete Volume objects parsed from the cast file, defaulting an empty namespace to "default" (or to the cast-file override).

func (*CastFile) HasParseErrors

func (cf *CastFile) HasParseErrors() bool

HasParseErrors returns true if any parsing errors were encountered

func (*CastFile) Lint

func (cf *CastFile) Lint() []error

Lint validates all specs in the cast file and returns a list of errors. It does not stop on first error; all validation errors are collected.

func (*CastFile) RestoreTemplateReferences

func (cf *CastFile) RestoreTemplateReferences(content string) string

RestoreTemplateReferences replaces template placeholders with their original template syntax

func (*CastFile) Validate

func (cf *CastFile) Validate() error

Validate runs Lint and returns a single error if any issues are found.

type Channel

type Channel struct {
	// Unique identifier.
	ID string `json:"id" yaml:"id"`

	// DNS-1123 cluster-unique name (what rules reference).
	Name string `json:"name" yaml:"name"`

	// Type is "webhook" or "slack" (a webhook preset).
	Type string `json:"type" yaml:"type"`

	// URL is the HTTP(S) endpoint POSTed on alert transitions. May contain
	// ${secret:namespace/name/key} references resolved at send time.
	URL string `json:"url" yaml:"url"`

	// Headers are added to the request. Values may contain
	// ${secret:namespace/name/key} references (e.g. an Authorization bearer
	// token), resolved at send time — never stored resolved.
	Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`

	// Body is an optional Go text/template for the request payload. Template
	// data: {{.Rule}} {{.State}} {{.PrevState}} {{.Value}} {{.Threshold}}
	// {{.Op}} {{.Window}} {{.LogQL}} {{.Since}} {{.Description}}. Empty uses
	// the default JSON payload (or the Slack preset for type slack).
	Body string `json:"body,omitempty" yaml:"body,omitempty"`

	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Channel is a named notification target referenced by AlertRule.Channels. One channel, many rules. The universal type is a templated webhook: URL + headers + an optional Go text/template body, which covers Slack, PagerDuty, Opsgenie, Discord, and HTTP email APIs (Resend, SendGrid, ...) with no provider-specific code. `type: slack` is a preset that defaults the body to Slack's incoming-webhook payload.

type ClickHouseConfig

type ClickHouseConfig struct {
	// DSN is the connection string (clickhouse://user:pass@host:9000/db).
	DSN string `yaml:"dsn,omitempty"`
	// Database is the target database (default "runesight").
	Database string `yaml:"database,omitempty"`
	// Table is the target log table (default "logs").
	Table string `yaml:"table,omitempty"`
	// AutoMigrate creates the database/table on first connect (default true).
	AutoMigrate bool `yaml:"auto_migrate,omitempty"`
	// StoragePolicy is the server-configured policy naming the hot + s3
	// volumes. Empty disables tiering.
	StoragePolicy string `yaml:"storage_policy,omitempty"`
	// S3Volume is the volume within StoragePolicy aged parts move to
	// (default "s3").
	S3Volume string `yaml:"s3_volume,omitempty"`
	// HotDays moves parts older than this to S3Volume. 0 keeps everything
	// on the hot disk.
	HotDays int `yaml:"hot_days,omitempty"`
}

ClickHouseConfig is the runefile block for the clickhouse observability backend. ClickHouse is local-disk-first; long retention is S3 tiering — a TTL move-to-volume against a server-configured storage policy (the policy and its S3 credentials live in ClickHouse server config, not here).

type ClientConfig

type ClientConfig struct {
	Timeout time.Duration `yaml:"timeout,omitempty"`
	Retries int           `yaml:"retries,omitempty"`
}

ClientConfig represents client configuration

type Cluster

type Cluster struct {
	// Unique identifier for the cluster
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the cluster
	Name string `json:"name" yaml:"name"`

	// Version of the cluster schema
	Version string `json:"version" yaml:"version"`

	// Nodes that are part of this cluster
	Nodes []Node `json:"nodes,omitempty" yaml:"nodes,omitempty"`

	// Services deployed in this cluster
	Services []Service `json:"services,omitempty" yaml:"services,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Cluster represents a collection of nodes running services.

func (*Cluster) Validate

func (c *Cluster) Validate() error

Validate validates the cluster configuration.

type ClusterNetwork

type ClusterNetwork struct {
	// CIDR is the service VIP range, e.g. "10.96.0.0/16". Set once at
	// bootstrap; changing it requires a cluster reset.
	CIDR string `json:"cidr"`

	// AllocatedVIPs maps serviceID → IP (string form, e.g. "10.96.0.7").
	// Stored as strings to keep JSON / proto round-trips stable.
	AllocatedVIPs map[string]string `json:"allocatedVIPs,omitempty"`

	// FreeList is the queue of IPs available for the next allocation.
	// IPs returned by Release reach FreeList only after the cooldown
	// period elapses. Stored as strings for the same reason as above.
	FreeList []string `json:"freeList,omitempty"`
}

ClusterNetwork is the cluster-wide VIP allocation state. It is committed via the OrderedLog by the VIP allocator and surfaced through the Admin API for tooling. There is exactly one ClusterNetwork per cluster, keyed by the literal name "cluster".

The allocator is the only writer; readers (CLI, dashboards) MUST treat the struct as opaque and avoid mutating it.

type ConfigResourceConfig

type ConfigResourceConfig struct {
	Limits *LimitsConfig `yaml:"limits,omitempty"`
}

ConfigResourceConfig holds limits for the top-level `config:` resource type (RUNE-016 ConfigMaps). Distinct from `secret.limits`.

type Configmap

type Configmap struct {
	// Unique identifier for the config
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the config (DNS-1123 unique name within a namespace)
	Name string `json:"name" yaml:"name"`

	// Namespace the config belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Configuration data (not encrypted)
	Data map[string]string `json:"data" yaml:"data"`

	// Current version number
	Version int `json:"version" yaml:"version"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`

	// OwnedBy is the system ownership stamp set when a runeset release manages
	// this configmap. See _docs/plugins/RUNESET_STATEFUL_RELEASES.md.
	OwnedBy *OwnedBy `json:"ownedBy,omitempty" yaml:"ownedBy,omitempty"`
}

Configmap represents a piece of non-sensitive configuration data.

type ConfigmapMount

type ConfigmapMount struct {
	// Name of the mount (for identification)
	Name string `json:"name" yaml:"name"`

	// Path where the config should be mounted
	MountPath string `json:"mountPath" yaml:"mountPath"`

	// Name of the config to mount
	ConfigmapName string `json:"configmapName" yaml:"configmapName"`

	// Optional: specific keys to project from the config
	Items []KeyToPath `json:"items,omitempty" yaml:"items,omitempty"`
}

ConfigmapMount defines a config to be mounted in a container.

type ConfigmapSpec

type ConfigmapSpec struct {
	// Human-readable name for the config (required)
	Name string `json:"name" yaml:"name"`

	// Namespace the config belongs to (optional, defaults to "default")
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

	// Config data
	Data map[string]string `json:"data" yaml:"data"`

	// Skip indicates this spec should be ignored by castfile parsing
	Skip bool `json:"skip,omitempty" yaml:"skip,omitempty"`
	// contains filtered or unexported fields
}

ConfigmapSpec represents the YAML specification for a config (flat form).

func (*ConfigmapSpec) GetName

func (c *ConfigmapSpec) GetName() string

Implement Spec interface for ConfigmapSpec

func (*ConfigmapSpec) GetNamespace

func (c *ConfigmapSpec) GetNamespace() string

func (*ConfigmapSpec) Kind

func (c *ConfigmapSpec) Kind() string

func (*ConfigmapSpec) ToConfigmap

func (c *ConfigmapSpec) ToConfigmap() (*Configmap, error)

ToConfigmap converts a ConfigmapSpec to a Configmap.

func (*ConfigmapSpec) UnmarshalYAML

func (c *ConfigmapSpec) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements custom unmarshalling so `data` can be provided either as a mapping (key: value) or as a sequence of {key, value} objects.

func (*ConfigmapSpec) Validate

func (c *ConfigmapSpec) Validate() error

Validate checks if a config specification is valid.

type DeletionOperation

type DeletionOperation struct {
	// Unique identifier for the operation
	ID string `json:"id"`

	// Namespace the service belongs to
	Namespace string `json:"namespace"`

	// Name of the service being deleted
	ServiceName string `json:"service_name"`

	// Total number of instances to delete
	TotalInstances int `json:"total_instances"`

	// Number of instances deleted so far
	DeletedInstances int `json:"deleted_instances"`

	// Number of failed instance deletions
	FailedInstances int `json:"failed_instances"`

	// Time the operation started
	StartTime time.Time `json:"start_time"`

	// Time the operation ended (if completed/failed/cancelled)
	EndTime *time.Time `json:"end_time,omitempty"`

	// Current status of the operation (combines previous status and phase)
	Status DeletionOperationStatus `json:"status"`

	// Whether this is a dry run operation
	DryRun bool `json:"dry_run"`

	// Reason for failure/cancellation if applicable
	FailureReason string `json:"failure_reason,omitempty"`

	// List of pending cleanup operations
	PendingOperations []string `json:"pending_operations,omitempty"`

	// Estimated completion time
	EstimatedCompletion *time.Time `json:"estimated_completion,omitempty"`

	// Finalizers that need to complete before deletion (ordered by execution)
	Finalizers []Finalizer `json:"finalizers,omitempty"`
}

DeletionOperation represents a deletion operation for a service

type DeletionOperationStatus

type DeletionOperationStatus string

DeletionOperationStatus represents the status of a deletion operation

const (
	// DeletionOperationStatusInitializing indicates the operation is being set up
	DeletionOperationStatusInitializing DeletionOperationStatus = "initializing"

	// DeletionOperationStatusDeletingInstances indicates instances are being deleted
	DeletionOperationStatusDeletingInstances DeletionOperationStatus = "deleting-instances"

	// DeletionOperationStatusRunningFinalizers indicates finalizers are executing
	DeletionOperationStatusRunningFinalizers DeletionOperationStatus = "running-finalizers"

	// DeletionOperationStatusCompleted indicates the operation completed successfully
	DeletionOperationStatusCompleted DeletionOperationStatus = "completed"

	// DeletionOperationStatusFailed indicates the operation failed
	DeletionOperationStatusFailed DeletionOperationStatus = "failed"
)

type DeletionRequest

type DeletionRequest struct {
	// Namespace of the service
	Namespace string `json:"namespace"`

	// Name of the service
	Name string `json:"name"`

	// Force deletion without confirmation
	Force bool `json:"force"`

	// Timeout for graceful shutdown
	TimeoutSeconds int32 `json:"timeout_seconds"`

	// Detach and return immediately
	Detach bool `json:"detach"`

	// Dry run mode
	DryRun bool `json:"dry_run"`

	// Grace period for graceful shutdown
	GracePeriod int32 `json:"grace_period"`

	// Immediate deletion without graceful shutdown
	Now bool `json:"now"`

	// Don't error if service doesn't exist
	IgnoreNotFound bool `json:"ignore_not_found"`

	// Optional finalizers to run
	Finalizers []string `json:"finalizers,omitempty"`
}

DeletionRequest represents a request to delete a service

type DeletionResponse

type DeletionResponse struct {
	// ID of the deletion operation
	DeletionID string `json:"deletion_id"`

	// Status of the deletion
	Status string `json:"status"`

	// Warning messages
	Warnings []string `json:"warnings,omitempty"`

	// Error messages
	Errors []string `json:"errors,omitempty"`

	// Whether cleanup was partial
	PartialCleanup bool `json:"partial_cleanup"`

	// Finalizers that will be executed
	Finalizers []Finalizer `json:"finalizers,omitempty"`
}

DeletionResponse represents the response from a deletion request

type DependencyRef

type DependencyRef struct {
	Service   string `json:"service,omitempty" yaml:"service,omitempty"`
	Secret    string `json:"secret,omitempty" yaml:"secret,omitempty"`
	Configmap string `json:"configmap,omitempty" yaml:"configmap,omitempty"`
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
}

DependencyRef is the normalized internal representation of a dependency It can represent Service, Secret, or Configmap dependencies. Exactly one of Service/Secret/Configmap should be set.

func (*DependencyRef) GetDependencyResourceName

func (d *DependencyRef) GetDependencyResourceName() string

func (*DependencyRef) GetDependencyResourceType

func (d *DependencyRef) GetDependencyResourceType() ResourceType

type DockerConfig

type DockerConfig struct {
	APIVersion                string                 `yaml:"api_version,omitempty"`
	FallbackAPIVersion        string                 `yaml:"fallback_api_version,omitempty"`
	NegotiationTimeoutSeconds int                    `yaml:"negotiation_timeout_seconds,omitempty"`
	LogMaxSize                string                 `yaml:"log_max_size,omitempty"`
	LogMaxFile                int                    `yaml:"log_max_file,omitempty"`
	Registries                []DockerRegistryConfig `yaml:"registries,omitempty"`
}

DockerConfig represents Docker runner configuration

type DockerRegistryAuth

type DockerRegistryAuth struct {
	Type       string            `yaml:"type,omitempty"` // basic | token | ecr
	Username   string            `yaml:"username,omitempty"`
	Password   string            `yaml:"password,omitempty"`
	Token      string            `yaml:"token,omitempty"`
	Region     string            `yaml:"region,omitempty"`
	FromSecret any               `yaml:"fromSecret,omitempty"` // string or {name,namespace}
	Bootstrap  bool              `yaml:"bootstrap,omitempty"`
	Manage     string            `yaml:"manage,omitempty"`
	Immutable  bool              `yaml:"immutable,omitempty"`
	Data       map[string]string `yaml:"data,omitempty"`
}

DockerRegistryAuth holds registry credentials (or a fromSecret reference). Mirrors internal/config.DockerRegistryAuth — see RUNE-018 for the secret-bootstrap semantics.

type DockerRegistryConfig

type DockerRegistryConfig struct {
	Name     string             `yaml:"name"`
	Registry string             `yaml:"registry"`
	Auth     DockerRegistryAuth `yaml:"auth,omitempty"`
}

DockerRegistryConfig is a single private-registry entry. Mirrors internal/config.DockerRegistryConfig.

type EgressRule

type EgressRule struct {
	To    []NetworkPolicyPeer `json:"to" yaml:"to"`
	Ports []string            `json:"ports,omitempty" yaml:"ports,omitempty"`
}

type EncryptionConfig

type EncryptionConfig struct {
	Enabled bool       `yaml:"enabled"`
	KEK     *KEKConfig `yaml:"kek,omitempty"`
}

EncryptionConfig represents encryption configuration

type Endpoint

type Endpoint struct {
	// Instance ID this endpoint belongs to
	InstanceID string `json:"instanceId" yaml:"instanceId"`

	// IP address for this endpoint
	IP string `json:"ip" yaml:"ip"`

	// Port for this endpoint
	Port int `json:"port" yaml:"port"`

	// Protocol for this endpoint
	Protocol string `json:"protocol,omitempty" yaml:"protocol,omitempty"`

	// Endpoint-specific metadata
	Metadata map[string]string `json:"metadata,omitempty" yaml:"metadata,omitempty"`

	// Health status for this endpoint
	Healthy bool `json:"healthy" yaml:"healthy"`

	// Last health check timestamp
	LastCheck time.Time `json:"lastCheck,omitempty" yaml:"lastCheck,omitempty"`
}

Endpoint represents a specific instance endpoint.

type EnvFromList

type EnvFromList []EnvFromSourceSpec

EnvFromList allows envFrom to be either a single item (mapping or scalar) or a list in YAML

func (*EnvFromList) UnmarshalYAML

func (l *EnvFromList) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML supports sequence, mapping, or scalar forms for envFrom

type EnvFromSource

type EnvFromSource struct {
	// Exactly one of these will be set
	SecretName    string `json:"secretName,omitempty" yaml:"secretName,omitempty"`
	ConfigmapName string `json:"configmapName,omitempty" yaml:"configmapName,omitempty"`

	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
	Prefix    string `json:"prefix,omitempty" yaml:"prefix,omitempty"`
}

EnvFromSource is the internal normalized representation of envFrom

type EnvFromSourceSpec

type EnvFromSourceSpec struct {
	// One of these must be set
	Secret    string `json:"secret,omitempty" yaml:"secret,omitempty"`
	Configmap string `json:"configmap,omitempty" yaml:"configmap,omitempty"`

	// Optional namespace; defaults to the service namespace
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

	// Optional prefix to apply to each imported key
	Prefix string `json:"prefix,omitempty" yaml:"prefix,omitempty"`

	// Raw holds the original scalar form (possibly a template placeholder) used during restoration
	Raw string `json:"-" yaml:"-"`
}

EnvFromSourceSpec defines an import source for environment variables

func (*EnvFromSourceSpec) UnmarshalYAML

func (e *EnvFromSourceSpec) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML allows envFrom entries to be specified as either a mapping (secret/configmap/namespace/prefix) or a shorthand scalar like "{{secret:name}}", "secret:name", "config:app-settings" or FQDN forms.

type Event

type Event struct {
	// ID is the stable, per-resource identifier "<kind>/<name>/<resourceSeq>".
	// It is the idempotency key for server-side dedup at any consumer.
	ID string `json:"id" yaml:"id"`

	// Seq is a node-global monotonic sequence number. It lets an
	// external consumer track delivery progress with a single cursor
	// (see EventLog.ListSince) instead of a per-resource map.
	Seq int64 `json:"seq" yaml:"seq"`

	// Namespace / Kind / Name identify the resource the event is about.
	// Kind is "Instance" | "Service" | "Volume" | "Node".
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
	Kind      string `json:"kind" yaml:"kind"`
	Name      string `json:"name" yaml:"name"`

	// UID ties the event to a specific incarnation of the resource
	// (e.g. one instance UUID), so `describe --previous` can separate
	// a dead incarnation's events from the live one's.
	UID string `json:"uid,omitempty" yaml:"uid,omitempty"`

	// Level is the event severity.
	Level EventLevel `json:"level" yaml:"level"`

	// Reason is the machine-readable slug (e.g. "VolumeNotReady").
	Reason string `json:"reason,omitempty" yaml:"reason,omitempty"`

	// Message is the human-readable sentence.
	Message string `json:"message" yaml:"message"`

	// FirstSeen / LastSeen bound the fold window: an event identical to
	// the most recent one for its resource (same Reason+Message+UID)
	// bumps LastSeen and Count instead of appending a new record.
	FirstSeen time.Time `json:"firstSeen" yaml:"firstSeen"`
	LastSeen  time.Time `json:"lastSeen" yaml:"lastSeen"`

	// Count is how many times the folded event has occurred (>=1).
	Count int `json:"count" yaml:"count"`
}

Event is one entry in a resource's time-ordered diagnostic trail (RUNE-126 Phase 2). Controllers emit an Event on every state transition and reconcile error; the EventRecorder folds, persists and serves them. Events are observability, not consensus state — they are node-local and never routed through OrderedLog/Raft.

See RUNE-126 §5.

type EventLevel

type EventLevel string

EventLevel is the severity of a resource Event.

const (
	// EventLevelInfo marks a normal lifecycle transition.
	EventLevelInfo EventLevel = "INFO"
	// EventLevelWarn marks a recoverable or retrying condition.
	EventLevelWarn EventLevel = "WARN"
	// EventLevelError marks a failure.
	EventLevelError EventLevel = "ERR"
)

type Exec

type Exec struct {
	// Command to execute
	Command []string `json:"command" yaml:"command"`

	// Environment variables
	Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`
}

Exec represents execution configuration for a command

type ExecOptions

type ExecOptions struct {
	// Command is the command to execute
	Command []string

	// Env is a map of environment variables to set for the command
	Env map[string]string

	// WorkingDir is the working directory for the command
	WorkingDir string

	// TTY indicates whether to allocate a pseudo-TTY
	TTY bool

	// TerminalWidth is the initial width of the terminal
	TerminalWidth uint32

	// TerminalHeight is the initial height of the terminal
	TerminalHeight uint32
}

ExecOptions defines options for executing a command in a running instance

type ExecStream

type ExecStream interface {
	// Write writes data to the standard input of the process
	Write(p []byte) (n int, err error)

	// Read reads data from the standard output of the process
	Read(p []byte) (n int, err error)

	// Stderr provides access to the standard error stream of the process
	Stderr() io.Reader

	// ResizeTerminal resizes the terminal (if TTY was enabled)
	ResizeTerminal(width, height uint32) error

	// Signal sends a signal to the process
	Signal(sigName string) error

	// ExitCode returns the exit code after the process has completed
	ExitCode() (int, error)

	// Close terminates the exec session and releases resources
	Close() error
}

ExecStream provides bidirectional communication with an exec session

type ExposeClientCert

type ExposeClientCert struct {
	// CASecret references a Secret holding a PEM CA bundle (data key
	// "ca.crt") used to verify the client certificate. Accepts the same
	// resource-ref shapes as ExposeServiceTLS.Secret.
	CASecret string `json:"caSecret" yaml:"caSecret"`

	// Mode is the verification strictness. v1 supports only "require"
	// (RequireAndVerifyClientCert); empty defaults to "require".
	Mode string `json:"mode,omitempty" yaml:"mode,omitempty"`
}

ExposeClientCert configures inbound mTLS for an exposed service.

type ExposeServiceTLS

type ExposeServiceTLS struct {
	// Secret references a Secret resource holding tls.crt + tls.key
	// for operator-supplied certificates. Accepts three shapes:
	//
	//   - "name"                       (resolved in the service's namespace)
	//   - "<namespace>/<name>"         (cross-namespace shorthand)
	//   - "secret:<name>.<ns>.rune"    (FQDN secret ref)
	//
	// Required when Mode is "manual".
	Secret string `json:"secret,omitempty" yaml:"secret,omitempty"`

	// Whether to automatically generate a TLS certificate
	Auto bool `json:"auto,omitempty" yaml:"auto,omitempty"`

	// Mode selects the certificate provisioning strategy.
	// Empty / "manual": operator supplies Secret.
	// "acme": ingress controller obtains a cert from Let's Encrypt
	// (HTTP-01) for Expose.Host. Auto implies Mode=acme.
	// See RUNE-066.
	Mode string `json:"mode,omitempty" yaml:"mode,omitempty"`
}

ExposeServiceTLS defines TLS configuration for exposed services.

func (*ExposeServiceTLS) IsACME

func (t *ExposeServiceTLS) IsACME() bool

IsACME reports whether the expose configuration requests ACME-managed TLS. The boolean Auto: true is treated as Mode=acme. Mode values "acme" and "auto" are accepted as synonyms.

type FailedInstanceRetentionConfig

type FailedInstanceRetentionConfig struct {
	// PerServiceCap is the max number of Failed tombstones kept per
	// service before the oldest is evicted. 0 disables the cap.
	PerServiceCap int `yaml:"per_service_cap,omitempty"`
	// TTL is the max age of a Failed tombstone before it is evicted
	// regardless of cap. 0 disables TTL.
	TTL time.Duration `yaml:"ttl,omitempty"`
	// SnapshotLogBytes caps the per-instance log snapshot captured into
	// Instance.LastLogs at eviction. 0 disables snapshotting. Reserved
	// for v2 — not yet honoured by the eviction path.
	SnapshotLogBytes int `yaml:"snapshot_log_bytes,omitempty"`
}

FailedInstanceRetentionConfig is the runefile-side view of the failed- instance retention policy. Parallel to internal/config.FailedInstanceRetention.

type Finalizer

type Finalizer struct {
	// Unique identifier for the finalizer
	ID string `json:"id"`

	// Type of finalizer
	Type FinalizerType `json:"type"`

	// Status of the finalizer
	Status FinalizerStatus `json:"status"`

	// Error message if finalizer failed
	Error string `json:"error,omitempty"`

	// Dependencies this finalizer has on other finalizers
	Dependencies []FinalizerDependency `json:"dependencies,omitempty"`

	// Timestamps
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`
}

Finalizer represents a cleanup operation that must complete before deletion

type FinalizerDependency

type FinalizerDependency struct {
	// The type of finalizer that must complete before this one
	DependsOn FinalizerType `json:"depends_on"`

	// Whether the dependency is required (true) or optional (false)
	Required bool `json:"required"`
}

FinalizerDependency represents a dependency between finalizers

type FinalizerInterface

type FinalizerInterface interface {
	GetID() string
	GetType() FinalizerType
	Execute(ctx context.Context, service *Service) error
	GetDependencies() []FinalizerDependency
	Validate(service *Service) error
}

FinalizerInterface for cleanup operations

type FinalizerStatus

type FinalizerStatus string

FinalizerStatus represents the status of a finalizer

const (
	FinalizerStatusPending   FinalizerStatus = "pending"
	FinalizerStatusRunning   FinalizerStatus = "running"
	FinalizerStatusCompleted FinalizerStatus = "completed"
	FinalizerStatusFailed    FinalizerStatus = "failed"
)

type FinalizerType

type FinalizerType string

FinalizerType represents the type of cleanup operation

const (
	// Resource cleanup finalizers
	FinalizerTypeVolumeCleanup  FinalizerType = "volume-cleanup"
	FinalizerTypeNetworkCleanup FinalizerType = "network-cleanup"
	FinalizerTypeSecretCleanup  FinalizerType = "secret-cleanup"
	FinalizerTypeConfigCleanup  FinalizerType = "config-cleanup"

	// Service-related finalizers
	FinalizerTypeServiceDeregister   FinalizerType = "service-deregister"
	FinalizerTypeLoadBalancerCleanup FinalizerType = "load-balancer-cleanup"

	// Instance-related finalizers
	FinalizerTypeInstanceCleanup FinalizerType = "instance-cleanup"
	FinalizerTypeProcessCleanup  FinalizerType = "process-cleanup"
)

type Function

type Function struct {
	// Unique identifier for the function
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the function
	Name string `json:"name" yaml:"name"`

	// Namespace the function belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Specification of the function
	Spec FunctionSpec `json:"spec" yaml:"spec"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Function represents a managed piece of user code and its execution environment.

type FunctionCode

type FunctionCode struct {
	// Inline source code
	Inline string `json:"inline,omitempty" yaml:"inline,omitempty"`
}

FunctionCode contains the function's source code, which can be specified inline or as a reference.

type FunctionDefinition

type FunctionDefinition struct {
	// Function metadata and spec
	Function struct {
		// Human-readable name for the function (required)
		Name string `json:"name" yaml:"name"`

		// Namespace the function belongs to (optional, defaults to "default")
		Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

		// Function specification
		Spec FunctionSpec `json:"spec" yaml:"spec"`
	} `json:"function" yaml:"function"`
}

FunctionSpec represents the YAML specification for a function.

func (*FunctionDefinition) ToFunction

func (f *FunctionDefinition) ToFunction() (*Function, error)

ToFunction converts a FunctionDefinition to a Function.

func (*FunctionDefinition) Validate

func (f *FunctionDefinition) Validate() error

Validate checks if a function definition is valid.

type FunctionInvocationRequest

type FunctionInvocationRequest struct {
	// Payload for the function (JSON-serializable object)
	Payload map[string]interface{} `json:"payload" yaml:"payload"`

	// Timeout override (optional)
	Timeout string `json:"timeout,omitempty" yaml:"timeout,omitempty"`

	// Asynchronous execution flag
	Async bool `json:"async,omitempty" yaml:"async,omitempty"`
}

FunctionInvocationRequest represents a request to invoke a function.

type FunctionNetworkPolicy

type FunctionNetworkPolicy struct {
	// Allowed outbound connections
	Allow []FunctionNetworkRule `json:"allow" yaml:"allow"`
}

FunctionNetworkPolicy defines what network connections a function is allowed to make.

type FunctionNetworkRule

type FunctionNetworkRule struct {
	// Target host or IP
	Host string `json:"host" yaml:"host"`

	// Allowed ports and protocols (e.g., ["80/tcp", "443/tcp"])
	Ports []string `json:"ports" yaml:"ports"`
}

FunctionNetworkRule defines a single allow rule for network connectivity.

type FunctionRun

type FunctionRun struct {
	// Unique identifier for the function run
	ID string `json:"id" yaml:"id"`

	// ID of the function that was executed
	FunctionID string `json:"functionId" yaml:"functionId"`

	// Namespace the function belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Input payload (JSON-serialized)
	Input string `json:"input,omitempty" yaml:"input,omitempty"`

	// Output result (JSON-serialized)
	Output string `json:"output,omitempty" yaml:"output,omitempty"`

	// Execution logs (stdout/stderr)
	Logs string `json:"logs,omitempty" yaml:"logs,omitempty"`

	// Execution status
	Status FunctionRunStatus `json:"status" yaml:"status"`

	// Error message (if status is Failed or TimedOut)
	Error string `json:"error,omitempty" yaml:"error,omitempty"`

	// Start time
	StartTime *time.Time `json:"startTime,omitempty" yaml:"startTime,omitempty"`

	// End time
	EndTime *time.Time `json:"endTime,omitempty" yaml:"endTime,omitempty"`

	// Duration in milliseconds
	DurationMs int64 `json:"durationMs,omitempty" yaml:"durationMs,omitempty"`

	// Invoker information (component/user that triggered the execution)
	InvokedBy string `json:"invokedBy,omitempty" yaml:"invokedBy,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
}

FunctionRun represents a single execution of a Function.

type FunctionRunStatus

type FunctionRunStatus string

FunctionRunStatus represents the execution status of a function run.

const (
	// FunctionRunStatusPending indicates the function execution is queued
	FunctionRunStatusPending FunctionRunStatus = "Pending"

	// FunctionRunStatusRunning indicates the function is currently executing
	FunctionRunStatusRunning FunctionRunStatus = "Running"

	// FunctionRunStatusSucceeded indicates the function completed successfully
	FunctionRunStatusSucceeded FunctionRunStatus = "Succeeded"

	// FunctionRunStatusFailed indicates the function execution failed
	FunctionRunStatusFailed FunctionRunStatus = "Failed"

	// FunctionRunStatusTimedOut indicates the function execution timed out
	FunctionRunStatusTimedOut FunctionRunStatus = "TimedOut"
)

type FunctionSpec

type FunctionSpec struct {
	// Runtime environment (e.g., python3.9, nodejs16, go1.18)
	Runtime string `json:"runtime" yaml:"runtime"`

	// Entrypoint handler (format depends on runtime, e.g., "main.handler")
	Handler string `json:"handler" yaml:"handler"`

	// Maximum execution time (e.g., "30s", "2m")
	Timeout string `json:"timeout" yaml:"timeout"`

	// Memory limit (e.g., "128Mi", "1Gi")
	MemoryLimit string `json:"memoryLimit" yaml:"memoryLimit"`

	// CPU limit (e.g., "100m", "0.5")
	CPULimit string `json:"cpuLimit,omitempty" yaml:"cpuLimit,omitempty"`

	// Function code
	Code FunctionCode `json:"code" yaml:"code"`

	// Static environment variables
	Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`

	// Network policy for the function
	NetworkPolicy *FunctionNetworkPolicy `json:"networkPolicy,omitempty" yaml:"networkPolicy,omitempty"`
}

FunctionSpec defines the execution environment and code for a Function.

type Gateway

type Gateway struct {
	// Unique identifier for the gateway
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the gateway
	Name string `json:"name" yaml:"name"`

	// Namespace the gateway belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Hostname for the gateway (for virtual hosting)
	Hostname string `json:"hostname,omitempty" yaml:"hostname,omitempty"`

	// Whether this is an internal gateway (not exposed outside the mesh)
	Internal bool `json:"internal" yaml:"internal"`

	// Port configurations for the gateway
	Ports []GatewayPort `json:"ports" yaml:"ports"`

	// TLS configuration options
	TLS *GatewayTLS `json:"tls,omitempty" yaml:"tls,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Gateway represents an ingress/egress gateway for the service mesh.

type GatewayPort

type GatewayPort struct {
	// Port number
	Port int `json:"port" yaml:"port"`

	// Protocol for this port (HTTP, HTTPS, TCP, etc.)
	Protocol string `json:"protocol" yaml:"protocol"`

	// Name for this port (optional)
	Name string `json:"name,omitempty" yaml:"name,omitempty"`
}

GatewayPort represents a port exposed by a gateway.

type GatewaySpec

type GatewaySpec struct {
	// Gateway metadata and configuration
	Gateway struct {
		// Human-readable name for the gateway (required)
		Name string `json:"name" yaml:"name"`

		// Namespace the gateway belongs to (optional, defaults to "default")
		Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

		// Hostname for the gateway (for virtual hosting)
		Hostname string `json:"hostname,omitempty" yaml:"hostname,omitempty"`

		// Whether this is an internal gateway (not exposed outside the mesh)
		Internal bool `json:"internal" yaml:"internal"`

		// Port configurations for the gateway
		Ports []GatewayPort `json:"ports" yaml:"ports"`

		// TLS configuration options
		TLS *GatewayTLS `json:"tls,omitempty" yaml:"tls,omitempty"`
	} `json:"gateway" yaml:"gateway"`
}

GatewaySpec represents the YAML specification for a gateway.

func (*GatewaySpec) ToGateway

func (g *GatewaySpec) ToGateway() (*Gateway, error)

ToGateway converts a GatewaySpec to a Gateway.

func (*GatewaySpec) Validate

func (g *GatewaySpec) Validate() error

Validate checks if a gateway specification is valid.

type GatewayTLS

type GatewayTLS struct {
	// Mode of TLS operation (PASSTHROUGH, SIMPLE, MUTUAL)
	Mode string `json:"mode" yaml:"mode"`

	// Secret name containing TLS credentials
	SecretName string `json:"secretName,omitempty" yaml:"secretName,omitempty"`

	// Minimum TLS version
	MinVersion string `json:"minVersion,omitempty" yaml:"minVersion,omitempty"`

	// Maximum TLS version
	MaxVersion string `json:"maxVersion,omitempty" yaml:"maxVersion,omitempty"`

	// Allow client certificate validation
	ClientCertificate bool `json:"clientCertificate,omitempty" yaml:"clientCertificate,omitempty"`
}

GatewayTLS represents TLS configuration for a gateway.

type HTTPRetryPolicy

type HTTPRetryPolicy struct {
	// Number of retry attempts
	Attempts int `json:"attempts" yaml:"attempts"`

	// Timeout per retry attempt in milliseconds
	PerTryTimeout int `json:"perTryTimeout,omitempty" yaml:"perTryTimeout,omitempty"`

	// HTTP status codes that trigger a retry
	RetryOn []int `json:"retryOn,omitempty" yaml:"retryOn,omitempty"`
}

HTTPRetryPolicy defines how request retries should be performed.

type HTTPRewrite

type HTTPRewrite struct {
	// URI to replace the matched path with
	URI string `json:"uri,omitempty" yaml:"uri,omitempty"`

	// Host to replace the request host with
	Host string `json:"host,omitempty" yaml:"host,omitempty"`
}

HTTPRewrite defines how the path and/or host should be rewritten.

type HTTPRoute

type HTTPRoute struct {
	// Path match for this route (e.g., "/api/v1")
	Path string `json:"path,omitempty" yaml:"path,omitempty"`

	// Path prefix match (e.g., "/api")
	PathPrefix string `json:"pathPrefix,omitempty" yaml:"pathPrefix,omitempty"`

	// HTTP methods this route applies to (GET, POST, etc.)
	Methods []string `json:"methods,omitempty" yaml:"methods,omitempty"`

	// Header matches required
	Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`

	// Query parameter matches required
	QueryParams map[string]string `json:"queryParams,omitempty" yaml:"queryParams,omitempty"`

	// Destination service and options
	Destination RouteDestination `json:"destination" yaml:"destination"`

	// Rewrite options
	Rewrite *HTTPRewrite `json:"rewrite,omitempty" yaml:"rewrite,omitempty"`

	// Response headers to be added
	AddResponseHeaders map[string]string `json:"addResponseHeaders,omitempty" yaml:"addResponseHeaders,omitempty"`

	// Request headers to be added
	AddRequestHeaders map[string]string `json:"addRequestHeaders,omitempty" yaml:"addRequestHeaders,omitempty"`

	// Timeout for this route in milliseconds
	Timeout int `json:"timeout,omitempty" yaml:"timeout,omitempty"`

	// Retry policy
	Retries *HTTPRetryPolicy `json:"retries,omitempty" yaml:"retries,omitempty"`

	// CORS policy
	CORS *CORSPolicy `json:"cors,omitempty" yaml:"cors,omitempty"`
}

HTTPRoute represents an HTTP routing rule.

type HealthCheck

type HealthCheck struct {
	// Liveness probe checks if the instance is running
	Liveness *Probe `json:"liveness,omitempty" yaml:"liveness,omitempty"`

	// Readiness probe checks if the instance is ready to receive traffic
	Readiness *Probe `json:"readiness,omitempty" yaml:"readiness,omitempty"`
}

HealthCheck represents health check configuration for a service.

func (*HealthCheck) Validate

func (h *HealthCheck) Validate() error

Validate validates the health check configuration.

type HealthCheckResult

type HealthCheckResult struct {
	Success    bool
	Message    string
	Duration   time.Duration
	CheckTime  time.Time
	InstanceID string
	CheckType  string
}

HealthCheckResult represents the result of a health check execution

type HealthFinalizerInterface

type HealthFinalizerInterface interface {
	RemoveInstance(instanceID string) error
}

type IngressCertState

type IngressCertState string

IngressCertState is a coarse-grained state for the certificate lifecycle. Operator-facing — keep the value space small.

const (
	// IngressCertPending means the orchestrator has accepted the
	// request but no certificate has been issued yet. The service
	// is reachable over plain HTTP only.
	IngressCertPending IngressCertState = "Pending"

	// IngressCertIssued means a usable certificate is in the
	// secret store and edge nodes are serving it.
	IngressCertIssued IngressCertState = "Issued"

	// IngressCertFailed means the most recent issuance attempt
	// failed. The orchestrator will retry per NextRetry; LastError
	// carries operator-facing detail.
	IngressCertFailed IngressCertState = "Failed"
)

type IngressCertStatus

type IngressCertStatus struct {
	// Host is the hostname the cert is issued for, e.g. api.example.com.
	Host string `json:"host" yaml:"host"`

	// State is one of Pending, Issued, Failed.
	State IngressCertState `json:"state" yaml:"state"`

	// IssuedAt is set when State transitions to Issued.
	IssuedAt *time.Time `json:"issuedAt,omitempty" yaml:"issuedAt,omitempty"`

	// ExpiresAt is the certificate NotAfter from the issued cert.
	ExpiresAt *time.Time `json:"expiresAt,omitempty" yaml:"expiresAt,omitempty"`

	// LastError is populated when State == Failed.
	LastError string `json:"lastError,omitempty" yaml:"lastError,omitempty"`

	// NextRetry is set when State == Failed; the orchestrator
	// schedules the next attempt at this time.
	NextRetry *time.Time `json:"nextRetry,omitempty" yaml:"nextRetry,omitempty"`
}

IngressCertStatus is the per-service cert status surfaced to the operator via `rune get service`. Mirrors the networking-layer implementation plan (RUNE-066).

type IngressConfig

type IngressConfig struct {
	HTTPAddr  string `yaml:"http_addr,omitempty"`
	HTTPSAddr string `yaml:"https_addr,omitempty"`
}

IngressConfig holds the bind addresses for the edge ingress (RUNE-067).

type IngressRule

type IngressRule struct {
	From  []NetworkPolicyPeer `json:"from" yaml:"from"`
	Ports []string            `json:"ports,omitempty" yaml:"ports,omitempty"`
}

type InitStep

type InitStep struct {
	// Name is the step's DNS-1123 identifier, unique within the
	// owning service's InitSteps.
	Name string `json:"name" yaml:"name"`

	// Image is the container image to run. Required when the parent
	// service Runtime is "container" (or unset). For Runtime "process"
	// the field is left empty and the step runs as a subprocess of
	// runed under the parent's process context.
	Image string `json:"image,omitempty" yaml:"image,omitempty"`

	// Command is the executable to run. There is no entrypoint
	// inheritance from the parent image — most init use cases want a
	// different command than the main container.
	Command string `json:"command" yaml:"command"`

	// Args are positional arguments passed to Command.
	Args []string `json:"args,omitempty" yaml:"args,omitempty"`

	// Env is merged on top of the parent service's env. Step-local
	// keys win on conflict.
	Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`

	// EnvFrom is merged with the parent's EnvFrom. Same precedence
	// rules apply.
	EnvFrom []EnvFromSource `json:"envFrom,omitempty" yaml:"envFrom,omitempty"`

	// Volumes is a filter over the parent service's volume mounts.
	// The default (a nil slice) inherits all parent volumes. An empty
	// non-nil slice mounts none. Each entry must reference a parent
	// VolumeMount.Name.
	Volumes []string `json:"volumes,omitempty" yaml:"volumes,omitempty"`

	// SecretMounts behaves identically to Volumes but for the
	// parent's SecretMounts.
	SecretMounts []string `json:"secretMounts,omitempty" yaml:"secretMounts,omitempty"`

	// ConfigmapMounts behaves identically to Volumes but for the
	// parent's ConfigmapMounts.
	ConfigmapMounts []string `json:"configmapMounts,omitempty" yaml:"configmapMounts,omitempty"`

	// Resources optionally overrides the inherited parent Resources.
	// Init for databases is often more I/O- and CPU-heavy than steady
	// state, so artificial low defaults would OOM-kill init.
	Resources *Resources `json:"resources,omitempty" yaml:"resources,omitempty"`

	// RunIf decides whether to execute the step on a given instance
	// start. Zero value is treated as Type=freshVolume.
	RunIf RunIf `json:"runIf,omitempty" yaml:"runIf,omitempty"`

	// Timeout is the per-step ceiling. Zero defers to the cast-level
	// timeout enforced by the controller.
	Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`

	// RestartPolicy controls per-step retry behaviour. Default
	// OnFailure (bounded retries inside the step).
	RestartPolicy InitStepRestartPolicy `json:"restartPolicy,omitempty" yaml:"restartPolicy,omitempty"`

	// SecurityContext optionally overrides container security knobs for
	// this step (seccomp profile, Linux capabilities, privileged). When
	// nil the step inherits the runtime defaults. Setting privileged=true
	// or seccompProfile.type=unconfined requires the services.privileged
	// policy verb; the server rejects requests that lack it.
	SecurityContext *SecurityContext `json:"securityContext,omitempty" yaml:"securityContext,omitempty"`
}

InitStep is a one-shot container or process executed before the main container of a Service starts. See RUNE-121.

type InitStepRestartPolicy

type InitStepRestartPolicy string

InitStepRestartPolicy controls per-step retry behaviour. The instance-level RestartPolicy does not apply to init steps because init failure must be observable rather than silently looped on.

const (
	// InitStepRestartOnFailure retries the step a small bounded number
	// of times with backoff before failing the instance. Default.
	InitStepRestartOnFailure InitStepRestartPolicy = "OnFailure"

	// InitStepRestartNever fails the instance on any non-zero exit.
	InitStepRestartNever InitStepRestartPolicy = "Never"
)

type InitStepState

type InitStepState struct {
	// Name matches Service.InitSteps[*].Name.
	Name string `json:"name" yaml:"name"`

	// Status is the lifecycle state.
	Status InitStepStatus `json:"status" yaml:"status"`

	// ExitCode is the process/container exit code. Zero by default;
	// only meaningful when Status is Succeeded or Failed.
	ExitCode int `json:"exitCode,omitempty" yaml:"exitCode,omitempty"`

	// StartedAt is the wall-clock time the step entered Running.
	StartedAt time.Time `json:"startedAt,omitempty" yaml:"startedAt,omitempty"`

	// FinishedAt is the wall-clock time the step left Running.
	FinishedAt time.Time `json:"finishedAt,omitempty" yaml:"finishedAt,omitempty"`

	// Attempts is the number of executions tried so far (>= 1 once
	// the step has run at least once). Used by RestartPolicy=OnFailure.
	Attempts int `json:"attempts,omitempty" yaml:"attempts,omitempty"`

	// Reason is one of the InitStepReason* slugs (empty on success).
	Reason string `json:"reason,omitempty" yaml:"reason,omitempty"`

	// Message is a single-line human explanation copied to
	// Service.StatusMessage on rollup.
	Message string `json:"message,omitempty" yaml:"message,omitempty"`

	// LogRef is an opaque handle the log subsystem can resolve to the
	// step's stdout/stderr slice.
	LogRef string `json:"logRef,omitempty" yaml:"logRef,omitempty"`
}

InitStepState records the per-instance, per-step execution outcome persisted on Instance.InitStates.

type InitStepStatus

type InitStepStatus string

InitStepStatus is the lifecycle state of one InitStep on one Instance.

const (
	InitStepStatusPending   InitStepStatus = "Pending"
	InitStepStatusRunning   InitStepStatus = "Running"
	InitStepStatusSucceeded InitStepStatus = "Succeeded"
	InitStepStatusFailed    InitStepStatus = "Failed"
	InitStepStatusSkipped   InitStepStatus = "Skipped"
)

type Instance

type Instance struct {
	NamespacedResource `json:"-" yaml:"-"`

	// Runner type for the instance
	Runner RunnerType `json:"runner" yaml:"runner"`

	// Unique identifier for the instance
	ID string `json:"id" yaml:"id"`

	// Namespace of the instance
	Namespace string `json:"namespace" yaml:"namespace"`

	// Human-readable name for the instance
	Name string `json:"name" yaml:"name"`

	// ID of the service this instance belongs to
	ServiceID string `json:"serviceId" yaml:"serviceId"`

	// Name of the service this instance belongs to
	ServiceName string `json:"serviceName" yaml:"serviceName"`

	// Ordinal is the per-replica slot index (0-based) assigned by the
	// reconciler at creation. It is the authoritative source of per-instance
	// identity for stable resources — notably per-replica volume claimTemplates,
	// which bind to "<mount>-<service>-<ordinal>". Keeping the ordinal as an
	// explicit field (rather than parsing it back out of Name) decouples that
	// binding from the instance-name format, so the name can move to a unique
	// per-lifetime form (RUNE issue #84) without breaking volume rebinding.
	Ordinal int `json:"ordinal" yaml:"ordinal"`

	// Labels are denormalized from the parent Service's user labels at creation
	// (and, once a placement scheduler exists, will also carry the assigned
	// node's topology labels — see CreateInstance). They form the user-defined
	// LogQL stream dimensions for this instance's logs and the substrate for
	// future node-affinity / topology-spread scheduling. Low-cardinality only —
	// high-cardinality data belongs in log content/fields, not stream labels.
	Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

	// ID of the node running this instance
	NodeID string `json:"nodeId" yaml:"nodeId"`

	// IP address assigned to this instance
	IP string `json:"ip" yaml:"ip"`

	// Status of the instance
	Status InstanceStatus `json:"status" yaml:"status"`

	// StatusReason is a short, machine-friendly slug for the current
	// Status, regardless of whether Status is a terminal failure state.
	// Mirrors Service.StatusReason / Volume.StatusReason. Set by the
	// reconciler on every status transition — including non-terminal
	// states such as Pending while a precondition (volume, secret,
	// image) is still unmet. Empty only when Status is Running.
	// Vocabulary is the slug set produced by classifyCreateError
	// (e.g. "VolumeNotReady", "StorageClassMissing", "SecretNotFound").
	// On a Failed/Stalled instance this converges with FailureReason.
	StatusReason string `json:"statusReason,omitempty" yaml:"statusReason,omitempty"`

	// Detailed status information
	StatusMessage string `json:"statusMessage,omitempty" yaml:"statusMessage,omitempty"`

	// Container ID or process ID
	ContainerID string `json:"containerId,omitempty" yaml:"containerId,omitempty"`

	// Process ID for process runner
	PID int `json:"pid,omitempty" yaml:"pid,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`

	// LastTransitionAt is when Status last changed value. Drives the
	// "Pending for 5m" age in `rune describe` and lets the reconciler
	// distinguish a genuinely-stuck resource from a freshly-updated
	// one. Distinct from UpdatedAt, which moves on any field write.
	// nil until the first reconciler-observed transition.
	LastTransitionAt *time.Time `json:"lastTransitionAt,omitempty" yaml:"lastTransitionAt,omitempty"`

	// Process-specific configuration for process runner
	Process *ProcessSpec `json:"process,omitempty" yaml:"process,omitempty"`

	// Execution configuration for commands and environment
	Exec *Exec `json:"exec,omitempty" yaml:"exec,omitempty"`

	// Resources requirements for the instance
	Resources *Resources `json:"resources,omitempty" yaml:"resources,omitempty"`

	// Environment variables for the instance
	Environment map[string]string `json:"environment,omitempty" yaml:"environment,omitempty"`

	// Metadata contains additional information about the instance
	// Use for storing system properties that aren't part of the core spec
	Metadata *InstanceMetadata `json:"metadata,omitempty" yaml:"metadata,omitempty"`

	// InitStates records the per-instance execution state for each
	// of the parent service's InitSteps (RUNE-121). One entry per
	// declared step, in declaration order. Empty for instances of
	// services with no init steps.
	InitStates []InitStepState `json:"initStates,omitempty" yaml:"initStates,omitempty"`

	// SecurityContext is inherited from the parent service's
	// SecurityContext and applied to the main container by the runner.
	// nil means runtime defaults.
	SecurityContext *SecurityContext `json:"securityContext,omitempty" yaml:"securityContext,omitempty"`

	// FailedAt is the timestamp the instance entered the Failed state.
	// Used by the reconciler's failed-instance retention GC to drive
	// per-service cap + TTL eviction. nil for instances that have never
	// failed.
	FailedAt *time.Time `json:"failedAt,omitempty" yaml:"failedAt,omitempty"`

	// FailureReason is a short, machine-friendly slug describing why the
	// instance failed (e.g. "HealthCheckFailure", "ImagePullFailed",
	// "OOMKilled"). Set at the moment of the Failed transition.
	FailureReason string `json:"failureReason,omitempty" yaml:"failureReason,omitempty"`

	// Usage is a live resource-usage sample attached by the API read path
	// from runners that implement the StatsProvider capability. TRANSIENT:
	// excluded from store serialization (json/yaml "-") so stale samples
	// are never persisted — it exists only on instances flowing through a
	// read RPC response.
	Usage *InstanceUsage `json:"-" yaml:"-"`

	// LastLogs is a snapshot of the last N bytes of the instance's stdout
	// and stderr, captured before the container is removed (either during
	// a restart-on-failure cycle or at retention-GC eviction). Lets
	// `rune logs --previous` show what the dead container said even after
	// the container itself is gone. Bounded by runed config
	// (failedInstanceRetention.snapshotLogBytes, default 200 KB).
	LastLogs []byte `json:"lastLogs,omitempty" yaml:"lastLogs,omitempty"`

	// LastLogsCapturedAt records when LastLogs was snapshotted so the
	// CLI can show "logs as of <time>" instead of pretending they're live.
	LastLogsCapturedAt *time.Time `json:"lastLogsCapturedAt,omitempty" yaml:"lastLogsCapturedAt,omitempty"`

	// LastLogsTruncated is true when LastLogs is a tail-only snapshot
	// (we hit the byte cap). The CLI shows a "[truncated]" marker so
	// operators know there was more output above what's preserved.
	LastLogsTruncated bool `json:"lastLogsTruncated,omitempty" yaml:"lastLogsTruncated,omitempty"`

	// CreateAttempts counts how many times the orchestrator has tried
	// to stand this instance record up (resolve mounts → run init →
	// runner.Create → runner.Start). Persisted on the record so a runed
	// restart does not reset progress against a stable precondition
	// failure (e.g. StorageClassMissing). Zeroed on first success.
	CreateAttempts int `json:"createAttempts,omitempty" yaml:"createAttempts,omitempty"`

	// ContainerEverCreatedAt is the wall-clock time `runner.Create`
	// first succeeded for this instance ID. The reconciler uses this
	// to distinguish "create has never succeeded" (precondition
	// failure — keep retrying the same record) from "container
	// vanished" (docker rm, host reboot — tombstone and recreate).
	// nil until the first successful runner.Create.
	ContainerEverCreatedAt *time.Time `json:"containerEverCreatedAt,omitempty" yaml:"containerEverCreatedAt,omitempty"`

	// NextCreateAttemptAt is the earliest wall-clock time the
	// reconciler may try CreateInstance again for this record.
	// Populated after every failed attempt as an exponential backoff
	// (30s → 1m → 2m → 4m → 5m cap). Reconciler ticks before this
	// time leave the record alone. nil means "ready now" or "not in
	// retry mode". Cleared on first success and on operator restart.
	NextCreateAttemptAt *time.Time `json:"nextCreateAttemptAt,omitempty" yaml:"nextCreateAttemptAt,omitempty"`
}

Instance represents a running copy of a service.

func (*Instance) Equals

func (i *Instance) Equals(other Resource) bool

Equals checks if two instances are functionally equivalent for watch purposes

func (*Instance) GetResourceType

func (i *Instance) GetResourceType() ResourceType

func (*Instance) String

func (i *Instance) String() string

String returns a unique identifier for the instance

func (*Instance) Validate

func (i *Instance) Validate() error

Validate validates the instance configuration.

type InstanceAction

type InstanceAction struct {
	Type       InstanceActionType
	Service    string
	Namespace  string
	InstanceID string
	Timestamp  time.Time
}

InstanceAction represents a pending action for an instance

type InstanceActionType

type InstanceActionType string

InstanceActionType represents an action to perform on an instance

const (
	// InstanceActionCreate indicates an instance should be created
	InstanceActionCreate InstanceActionType = "create"

	// InstanceActionUpdate indicates an instance should be updated
	InstanceActionUpdate InstanceActionType = "update"

	// InstanceActionDelete indicates an instance should be deleted
	InstanceActionDelete InstanceActionType = "delete"
)

type InstanceFinalizerInterface

type InstanceFinalizerInterface interface {
	StopInstance(ctx context.Context, instance *Instance) error
	DeleteInstance(ctx context.Context, instance *Instance) error
}

type InstanceHealthStatus

type InstanceHealthStatus struct {
	InstanceID  string
	Liveness    bool
	Readiness   bool
	LastChecked time.Time
}

InstanceHealthStatus represents the health status of an instance

type InstanceIdentity

type InstanceIdentity struct {
	// InstanceID is the orchestrator-assigned instance ID. Useful
	// for log correlation; not used for matching.
	InstanceID string `json:"instanceId" yaml:"instanceId"`

	// Service is the service name (no namespace).
	Service string `json:"service" yaml:"service"`

	// Namespace the service belongs to.
	Namespace string `json:"namespace" yaml:"namespace"`
}

InstanceIdentity is the minimum tuple needed to attribute a connection's source IP to a managed service.

type InstanceMetadata

type InstanceMetadata struct {
	// Image is the image that the instance is running
	Image string `json:"image,omitempty" yaml:"image,omitempty"`

	// Command is the executable to run inside the container,
	// propagated from Service.Command. Maps to Docker's Entrypoint:
	// it replaces the image's baked-in ENTRYPOINT. Empty leaves the
	// image's ENTRYPOINT untouched.
	Command string `json:"command,omitempty" yaml:"command,omitempty"`

	// Args are positional arguments to Command, propagated from
	// Service.Args. Maps to Docker's Cmd: it replaces the image's
	// baked-in CMD. nil leaves the image's CMD untouched.
	Args []string `json:"args,omitempty" yaml:"args,omitempty"`

	// ImagePull controls when the runner pulls the container image
	// ("always", "missing", "never"). Propagated from the parent
	// Service spec; empty defaults to "always".
	ImagePull string `json:"imagePull,omitempty" yaml:"imagePull,omitempty"`

	// ServiceGeneration is the generation of the service that the instance belongs to
	ServiceGeneration int64 `json:"serviceGeneration,omitempty" yaml:"serviceGeneration,omitempty"`

	// DeletionTimestamp is the timestamp when the instance was marked for deletion
	DeletionTimestamp *time.Time `json:"deletionTimestamp,omitempty" yaml:"deletionTimestamp,omitempty"`

	// RestartCount is the number of times this instance has been restarted
	RestartCount int `json:"restartCount,omitempty" yaml:"restartCount,omitempty"`

	// SecretMounts contains the resolved secret mount information for this instance
	SecretMounts []ResolvedSecretMount `json:"secretMounts,omitempty" yaml:"secretMounts,omitempty"`

	// ConfigmapMounts contains the resolved config mount information for this instance
	ConfigmapMounts []ResolvedConfigmapMount `json:"configMounts,omitempty" yaml:"configMounts,omitempty"`

	// VolumeMounts contains the resolved volume mount information for
	// this instance: each entry maps a Service.VolumeMount to the
	// concrete host-side source path produced by the storage driver.
	// Populated by the orchestrator's instance controller from the bound
	// Volume's Handle.
	VolumeMounts []ResolvedVolumeMount `json:"volumeMounts,omitempty" yaml:"volumeMounts,omitempty"`

	// Ports declared by the service (propagated for runner use)
	Ports []ServicePort `json:"ports,omitempty" yaml:"ports,omitempty"`

	// Expose specification from the service (propagated for runner use)
	Expose *ServiceExpose `json:"expose,omitempty" yaml:"expose,omitempty"`

	// Resolved exposed endpoint on host (best-effort)
	ExposedHost     string `json:"exposedHost,omitempty" yaml:"exposedHost,omitempty"`
	ExposedHostPort int    `json:"exposedHostPort,omitempty" yaml:"exposedHostPort,omitempty"`

	// ContainerIP is the IP assigned to the container on its primary
	// Docker network. Recorded by the runner on Start; consumed by the
	// agent to map source IPs to service identity for policy
	// enforcement.
	ContainerIP string `json:"containerIp,omitempty" yaml:"containerIp,omitempty"`
}

InstanceMetadata contains additional information about the instance

type InstanceStatus

type InstanceStatus string

InstanceStatus represents the current status of an instance.

const (
	// InstanceStatusPending indicates the instance is being created.
	InstanceStatusPending InstanceStatus = "Pending"

	// InstanceStatusRunning indicates the instance is running.
	InstanceStatusRunning InstanceStatus = "Running"

	// InstanceStatusStopped indicates the instance has stopped.
	InstanceStatusStopped InstanceStatus = "Stopped"

	// InstanceStatusFailed indicates the instance failed to start or crashed.
	InstanceStatusFailed InstanceStatus = "Failed"

	// InstanceStatusDeleted indicates the instance has been marked for deletion
	// but is retained in the store for a period before garbage collection.
	InstanceStatusDeleted InstanceStatus = "Deleted"

	// InstanceStatusTerminating indicates the instance is actively being
	// torn down — runner.Stop/Remove are in flight but haven't completed.
	// Without this, an instance whose parent service has just been
	// deleted (or which the reconciler is otherwise GC'ing) keeps
	// reporting Running until the graceful-shutdown timeout finishes,
	// giving operators a misleading "Running" view for ~10s.
	// Mirrors K8s' Pod.Phase=Terminating.
	InstanceStatusTerminating InstanceStatus = "Terminating"

	// InstanceStatusStalled indicates create has failed too many times
	// with a stable precondition error (StorageClassMissing, secret
	// missing, image-pull error) and the reconciler has stopped
	// auto-retrying until an operator intervenes. The slot is still
	// held by this record; operators unstick it with
	// `rune restart instance` or `rune cast` (new service generation).
	// Mirrors the volume controller's ProvisionRetriesExhausted shape.
	InstanceStatusStalled InstanceStatus = "Stalled"

	// Process runner specific statuses
	InstanceStatusCreated  InstanceStatus = "Created"
	InstanceStatusStarting InstanceStatus = "Starting"
	InstanceStatusExited   InstanceStatus = "Exited"
	InstanceStatusUnknown  InstanceStatus = "Unknown"
)
const InstanceStatusInitializing InstanceStatus = "Initializing"

InstanceStatusInitializing is the new instance phase between Pending (volumes bound) and Starting (main container Created/Start dispatched).

type InstanceStatusInfo

type InstanceStatusInfo struct {
	Status        InstanceStatus
	StatusMessage string
	InstanceID    string
	NodeID        string
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

InstanceStatusInfo contains information about an instance's status

type InstanceUsage

type InstanceUsage struct {
	// CPUPercent is CPU usage as a share of the WHOLE HOST, 0–100 — the
	// same denominator as node-level CPU on HealthService, so instance
	// bars and node bars compare 1:1. Negative when unknown.
	CPUPercent float64

	// MemUsedBytes is memory used in bytes (cgroup usage minus inactive
	// file cache, matching `docker stats` semantics).
	MemUsedBytes uint64

	// MemLimitBytes is the container's cgroup memory limit, which equals
	// the host total when the container is uncapped. 0 when unknown.
	MemLimitBytes uint64
}

InstanceUsage is a point-in-time resource-usage sample for one instance, reported by a runner that implements the StatsProvider capability.

type Job

type Job struct {
	// Unique identifier for the job
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the job
	Name string `json:"name" yaml:"name"`

	// Namespace the job belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Schedule in cron format (if this is a scheduled job)
	Schedule string `json:"schedule,omitempty" yaml:"schedule,omitempty"`

	// Template defining the job execution environment
	Template JobTemplate `json:"template" yaml:"template"`

	// Optional array job configuration
	Array *JobArray `json:"array,omitempty" yaml:"array,omitempty"`

	// Retry policy for failed job runs
	RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty" yaml:"retryPolicy,omitempty"`

	// How to handle concurrent runs (for scheduled jobs)
	ConcurrencyPolicy string `json:"concurrencyPolicy,omitempty" yaml:"concurrencyPolicy,omitempty"`

	// Number of successful run records to keep
	SuccessfulRunsHistoryLimit int `json:"successfulRunsHistoryLimit,omitempty" yaml:"successfulRunsHistoryLimit,omitempty"`

	// Number of failed run records to keep
	FailedRunsHistoryLimit int `json:"failedRunsHistoryLimit,omitempty" yaml:"failedRunsHistoryLimit,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Job represents a short-lived workload that runs to completion.

func (*Job) CreateJobRun

func (j *Job) CreateJobRun(arrayIndex int) *JobRun

CreateJobRun creates a new JobRun for a Job.

type JobArray

type JobArray struct {
	// Number of runs to create in the array
	Count int `json:"count" yaml:"count"`

	// Optional parallelism limit (max concurrent runs)
	Parallelism int `json:"parallelism,omitempty" yaml:"parallelism,omitempty"`
}

JobArray defines parameters for array jobs (multiple parallel runs).

type JobFile

type JobFile struct {
	// Job definition
	Job *JobSpec `json:"job,omitempty" yaml:"job,omitempty"`

	// Multiple job definitions
	Jobs []JobSpec `json:"jobs,omitempty" yaml:"jobs,omitempty"`
}

JobFile represents a file containing job definitions.

type JobRun

type JobRun struct {
	// Unique identifier for the job run
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the job run
	Name string `json:"name" yaml:"name"`

	// ID of the job this run belongs to
	JobID string `json:"jobId" yaml:"jobId"`

	// Namespace the job run belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Node this job run is/was scheduled on
	NodeID string `json:"nodeId,omitempty" yaml:"nodeId,omitempty"`

	// For array jobs, the index of this run in the array
	ArrayIndex int `json:"arrayIndex,omitempty" yaml:"arrayIndex,omitempty"`

	// Status of the job run
	Status JobRunStatus `json:"status" yaml:"status"`

	// Detailed status message
	StatusMessage string `json:"statusMessage,omitempty" yaml:"statusMessage,omitempty"`

	// Exit code if the job has completed
	ExitCode int `json:"exitCode,omitempty" yaml:"exitCode,omitempty"`

	// Number of restart attempts so far
	RestartCount int `json:"restartCount,omitempty" yaml:"restartCount,omitempty"`

	// Start time
	StartTime *time.Time `json:"startTime,omitempty" yaml:"startTime,omitempty"`

	// Completion time
	CompletionTime *time.Time `json:"completionTime,omitempty" yaml:"completionTime,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

JobRun represents a single execution of a Job.

type JobRunStatus

type JobRunStatus string

JobRunStatus represents the current status of a job run.

const (
	// JobRunStatusPending indicates the job run is waiting to be scheduled
	JobRunStatusPending JobRunStatus = "Pending"

	// JobRunStatusRunning indicates the job run is currently executing
	JobRunStatusRunning JobRunStatus = "Running"

	// JobRunStatusSucceeded indicates the job run completed successfully
	JobRunStatusSucceeded JobRunStatus = "Succeeded"

	// JobRunStatusFailed indicates the job run failed
	JobRunStatusFailed JobRunStatus = "Failed"
)

type JobSpec

type JobSpec struct {
	// Human-readable name for the job (required)
	Name string `json:"name" yaml:"name"`

	// Namespace the job belongs to (optional, defaults to "default")
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

	// Schedule in cron format (if this is a scheduled job)
	Schedule string `json:"schedule,omitempty" yaml:"schedule,omitempty"`

	// Template defining the job execution environment
	Template JobTemplate `json:"template" yaml:"template"`

	// Optional array job configuration
	Array *JobArray `json:"array,omitempty" yaml:"array,omitempty"`

	// Retry policy for failed job runs
	RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty" yaml:"retryPolicy,omitempty"`

	// How to handle concurrent runs (for scheduled jobs)
	ConcurrencyPolicy string `json:"concurrencyPolicy,omitempty" yaml:"concurrencyPolicy,omitempty"`

	// Number of successful run records to keep
	SuccessfulRunsHistoryLimit int `json:"successfulRunsHistoryLimit,omitempty" yaml:"successfulRunsHistoryLimit,omitempty"`

	// Number of failed run records to keep
	FailedRunsHistoryLimit int `json:"failedRunsHistoryLimit,omitempty" yaml:"failedRunsHistoryLimit,omitempty"`
}

JobSpec represents the YAML specification for a job.

func (*JobSpec) ToJob

func (j *JobSpec) ToJob() (*Job, error)

ToJob converts a JobSpec to a Job.

func (*JobSpec) Validate

func (j *JobSpec) Validate() error

Validate checks if a job specification is valid.

type JobTemplate

type JobTemplate struct {
	// Container image for the job
	Image string `json:"image" yaml:"image"`

	// Command to run in the container (overrides image CMD)
	Command string `json:"command,omitempty" yaml:"command,omitempty"`

	// Arguments to the command
	Args []string `json:"args,omitempty" yaml:"args,omitempty"`

	// Environment variables for the job
	Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`

	// Resource requirements for the job
	Resources Resources `json:"resources,omitempty" yaml:"resources,omitempty"`

	// Volumes to mount in the job container
	Volumes []VolumeMount `json:"volumes,omitempty" yaml:"volumes,omitempty"`

	// Secret mounts
	SecretMounts []SecretMount `json:"secretMounts,omitempty" yaml:"secretMounts,omitempty"`

	// Config mounts
	ConfigmapMounts []ConfigmapMount `json:"configmapMounts,omitempty" yaml:"configmapMounts,omitempty"`
}

JobTemplate defines the execution environment for a job.

type KEKConfig

type KEKConfig struct {
	Source     string            `yaml:"source,omitempty"`
	File       string            `yaml:"file,omitempty"`
	Passphrase *PassphraseConfig `yaml:"passphrase,omitempty"`
}

KEKConfig represents Key Encryption Key configuration

type KeyToPath

type KeyToPath struct {
	// Key in the Secret or Config
	Key string `json:"key" yaml:"key"`

	// Path where the key should be mounted (relative to mount point)
	Path string `json:"path" yaml:"path"`
}

KeyToPath defines mapping from a key in a Secret/Config to a path in the mount.

type LimitsConfig

type LimitsConfig struct {
	MaxObjectBytes   int `yaml:"max_object_bytes,omitempty"`
	MaxKeyNameLength int `yaml:"max_key_name_length,omitempty"`
}

LimitsConfig mirrors store.Limits as it appears in the runefile. Field tags use snake_case for consistency with the rest of the file even though store.Limits itself is untagged (viper's default behaviour is to lowercase field names with no separator, but in practice runefiles in the wild use snake_case here — keep both shapes valid).

type LocalInstances

type LocalInstances struct {
	// NodeID is the identity of the node these instances live on.
	NodeID string `json:"nodeId" yaml:"nodeId"`

	// Instances maps a container IP (e.g. "172.17.0.5") to the
	// service identity that owns it.
	Instances map[string]InstanceIdentity `json:"instances" yaml:"instances"`
}

LocalInstances is the per-node identity table maintained by the orchestrator and consumed by each agent. Each agent watches only its own node's record; the table maps a container IP observed at the agent's data plane to the (service, namespace) tuple that owns the container, so policy enforcement can resolve same-node source IPs back to a service identity without a service-mesh-style sidecar.

Cross-node peer identity is intentionally not derived from this table: a connection arriving at an agent from a different node originates from the remote agent's proxy, not the original container. Cross-node policy uses CIDR/namespace selectors only until data-plane mTLS lands.

type LogConfig

type LogConfig struct {
	Level  string `yaml:"level,omitempty"`
	Format string `yaml:"format,omitempty"`
}

LogConfig represents logging configuration

type LogOptions

type LogOptions struct {
	Follow     bool
	Since      time.Time
	Until      time.Time
	Tail       int
	Timestamps bool
	ShowLogs   bool   // Show container/process logs
	ShowEvents bool   // Show lifecycle events
	ShowStatus bool   // Show status changes
	Pattern    string // Filter logs by pattern
}

LogOptions defines options for retrieving logs

type LokiConfig

type LokiConfig struct {
	// URL is the Loki HTTP endpoint (e.g. http://loki:3100).
	URL string `yaml:"url,omitempty"`
	// TenantID is sent as X-Scope-OrgID for multi-tenant Loki.
	TenantID string `yaml:"tenant_id,omitempty"`
}

LokiConfig is the runefile block for the loki observability backend. Loki is object-storage-native (no tiering knobs here — point Loki itself at a bucket); this block only says where Loki is.

type MemoryConfig

type MemoryConfig struct {
	DefaultRequest string `yaml:"default_request,omitempty"`
	DefaultLimit   string `yaml:"default_limit,omitempty"`
}

MemoryConfig represents memory resource configuration

type Namespace

type Namespace struct {
	// Unique identifier for the namespace
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the namespace
	Name string `json:"name" yaml:"name"`

	// Optional description for the namespace
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// Optional resource quotas for this namespace
	Quota *NamespaceQuota `json:"quota,omitempty" yaml:"quota,omitempty"`

	// Labels attached to the namespace for organization
	Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Namespace represents a logical boundary for isolation and scoping of resources.

type NamespaceQuota

type NamespaceQuota struct {
	// Maximum CPU allocation for all resources in the namespace (millicores)
	CPU int64 `json:"cpu,omitempty" yaml:"cpu,omitempty"`

	// Maximum memory allocation for all resources in the namespace (bytes)
	Memory int64 `json:"memory,omitempty" yaml:"memory,omitempty"`

	// Maximum storage allocation for all resources in the namespace (bytes)
	Storage int64 `json:"storage,omitempty" yaml:"storage,omitempty"`

	// Maximum number of services allowed in the namespace
	Services int `json:"services,omitempty" yaml:"services,omitempty"`

	// Maximum number of jobs allowed in the namespace
	Jobs int `json:"jobs,omitempty" yaml:"jobs,omitempty"`

	// Maximum number of instances (all services combined) allowed in the namespace
	Instances int `json:"instances,omitempty" yaml:"instances,omitempty"`
}

NamespaceQuota represents resource quotas for a namespace.

type NamespaceSpec

type NamespaceSpec struct {
	// Human-readable name for the namespace (required)
	Name string `json:"name" yaml:"name"`

	// Optional description for the namespace
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// Optional resource quotas for this namespace
	Quota *NamespaceQuota `json:"quota,omitempty" yaml:"quota,omitempty"`

	// Labels attached to the namespace for organization
	Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
}

NamespaceSpec represents the YAML specification for a namespace.

func (*NamespaceSpec) ToNamespace

func (n *NamespaceSpec) ToNamespace() (*Namespace, error)

ToNamespace converts a NamespaceSpec to a Namespace.

func (*NamespaceSpec) Validate

func (n *NamespaceSpec) Validate() error

Validate checks if a namespace specification is valid.

type NamespacedName

type NamespacedName struct {
	Namespace string `json:"namespace" yaml:"namespace"`
	Name      string `json:"name" yaml:"name"`
}

NamespacedName is a struct that contains a namespace and a name.

func (*NamespacedName) GetName

func (n *NamespacedName) GetName() string

func (*NamespacedName) NamespacedName

func (n *NamespacedName) NamespacedName() NamespacedName

func (*NamespacedName) String

func (n *NamespacedName) String() string

type NamespacedResource

type NamespacedResource interface {
	NamespacedName() NamespacedName
	GetID() string // For resources that also have an ID
	GetResourceType() ResourceType
}

type NetworkPolicyPeer

type NetworkPolicyPeer struct {
	Service         string            `json:"service,omitempty" yaml:"service,omitempty"`
	Namespace       string            `json:"namespace,omitempty" yaml:"namespace,omitempty"`
	ServiceSelector map[string]string `json:"serviceSelector,omitempty" yaml:"serviceSelector,omitempty"`
	CIDR            string            `json:"cidr,omitempty" yaml:"cidr,omitempty"`
}

type NetworkingConfig

type NetworkingConfig struct {
	ClusterCIDR string `yaml:"cluster_cidr,omitempty"`
	DevMode     bool   `yaml:"dev_mode,omitempty"`
}

NetworkingConfig holds the networking-layer settings (RUNE-040..067).

type Node

type Node struct {
	// Unique identifier for the node
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the node
	Name string `json:"name" yaml:"name"`

	// IP address or hostname of the node
	Address string `json:"address" yaml:"address"`

	// Labels attached to the node for scheduling decisions
	Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

	// Available resources on this node
	Resources NodeResources `json:"resources" yaml:"resources"`

	// Status of the node
	Status NodeStatus `json:"status" yaml:"status"`

	// StatusReason is a short, machine-friendly slug explaining the
	// current Status (e.g. "HeartbeatTimeout", "DrainRequested").
	// Mirrors Service/Instance/Volume StatusReason. Empty when the
	// node is Ready.
	StatusReason string `json:"statusReason,omitempty" yaml:"statusReason,omitempty"`

	// StatusMessage is a human-readable sentence explaining StatusReason,
	// surfaced by `rune describe node`.
	StatusMessage string `json:"statusMessage,omitempty" yaml:"statusMessage,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last heartbeat timestamp
	LastHeartbeat time.Time `json:"lastHeartbeat" yaml:"lastHeartbeat"`
}

Node represents a machine that can run service instances.

func (*Node) Validate

func (n *Node) Validate() error

Validate validates the node configuration.

type NodeConfig

type NodeConfig struct {
	Role string `yaml:"role,omitempty"`
}

NodeConfig holds per-node placement metadata (edge / worker / leader).

type NodeResources

type NodeResources struct {
	// Available CPU in millicores (1000m = 1 CPU)
	CPU int64 `json:"cpu" yaml:"cpu"`

	// Available memory in bytes
	Memory int64 `json:"memory" yaml:"memory"`
}

NodeResources represents the resources available on a node.

type NodeStatus

type NodeStatus string

NodeStatus represents the current status of a node.

const (
	// NodeStatusReady indicates the node is ready to accept instances.
	NodeStatusReady NodeStatus = "Ready"

	// NodeStatusNotReady indicates the node is not ready.
	NodeStatusNotReady NodeStatus = "NotReady"

	// NodeStatusDraining indicates the node is being drained of instances.
	NodeStatusDraining NodeStatus = "Draining"
)

type ObservabilityConfig

type ObservabilityConfig struct {
	// Enabled turns the forwarder + log store on. Default false (opt-in):
	// the embedded store is lightweight but logging every workload line is
	// an operator choice, so a bare install stays on the live ephemeral
	// stream until [observability] is switched on.
	Enabled bool `yaml:"enabled,omitempty"`

	// Backend selects the log store: embedded (default, in-process), or the
	// optional clickhouse / loki sinks.
	Backend string `yaml:"backend,omitempty"`

	// RetentionDays bounds record age: the embedded store's sweep, and the
	// ClickHouse table's DELETE TTL. 0 uses the backend default. Loki manages
	// its own retention server-side.
	RetentionDays int `yaml:"retention_days,omitempty"`

	// Loki configures the loki backend. Parallel to internal/config.LokiConfig.
	Loki *LokiConfig `yaml:"loki,omitempty"`

	// ClickHouse configures the clickhouse backend, including S3 tiering.
	// Parallel to internal/config.ClickHouseConfig.
	ClickHouse *ClickHouseConfig `yaml:"clickhouse,omitempty"`
}

ObservabilityConfig is the runefile-side view of the native observability (RuneSight) subsystem. Parallel to internal/config.Observability.

Example:

observability:
  enabled: true
  backend: embedded        # embedded | clickhouse | loki
  retention_days: 7
  loki:                    # only for backend: loki
    url: http://loki:3100
    tenant_id: ""
  clickhouse:              # only for backend: clickhouse
    dsn: clickhouse://user:pass@host:9000/runesight
    auto_migrate: true
    storage_policy: ""     # enables S3 tiering when set
    hot_days: 7

type OwnedBy

type OwnedBy struct {
	// Release is the owning release name.
	Release string `json:"release" yaml:"release"`
	// Revision is the release revision that created or last touched the resource.
	Revision int `json:"revision" yaml:"revision"`
	// Manager identifies what manages the resource; "runeset" today.
	Manager string `json:"manager" yaml:"manager"`
}

OwnedBy is the system back-pointer stamped into an owned resource's metadata (NOT user labels), so GC and drift detection never depend on user edits.

type OwnerRef

type OwnerRef struct {
	ResourceType ResourceType `json:"resourceType" yaml:"resourceType"`
	Namespace    string       `json:"namespace" yaml:"namespace"`
	Name         string       `json:"name" yaml:"name"`
}

OwnerRef points to a single resource managed (or referenced) by a Release. The Namespace is carried per-ref so a release can span namespaces (D1).

func (OwnerRef) Key

func (o OwnerRef) Key() string

Key returns the canonical "type/namespace/name" identity of a ref.

type PassphraseConfig

type PassphraseConfig struct {
	Enabled bool   `yaml:"enabled"`
	Env     string `yaml:"env,omitempty"`
}

PassphraseConfig represents passphrase configuration

type PluginConfig

type PluginConfig struct {
	Dir     string   `yaml:"dir,omitempty"`
	Enabled []string `yaml:"enabled,omitempty"`
}

PluginConfig represents plugin configuration

type Policy

type Policy struct {
	ID          string       `json:"id" yaml:"id"`
	Name        string       `json:"name" yaml:"name"` // DNS-1123 unique name within a namespace
	Description string       `json:"description,omitempty" yaml:"description,omitempty"`
	Rules       []PolicyRule `json:"rules" yaml:"rules"`
	Builtin     bool         `json:"builtin" yaml:"builtin"`
}

Policy represents a named set of permission rules

func (*Policy) GetID

func (p *Policy) GetID() string

func (*Policy) GetResourceType

func (p *Policy) GetResourceType() ResourceType

type PolicyRule

type PolicyRule struct {
	Resource  string   `json:"resource" yaml:"resource"`
	Verbs     []string `json:"verbs" yaml:"verbs"`
	Namespace string   `json:"namespace,omitempty" yaml:"namespace,omitempty"`
}

PolicyRule defines a single permission rule within a policy

type Probe

type Probe struct {
	// Type of probe (http, tcp, exec)
	Type string `json:"type" yaml:"type"`

	// HTTP path for http probe
	Path string `json:"path,omitempty" yaml:"path,omitempty"`

	// Host overrides the default probe target. Empty means use the
	// instance's container IP (production) or localhost (process
	// runner / dev fallback). Set this to "127.0.0.1" when targeting
	// a hostPort published by the service on macOS Docker Desktop.
	Host string `json:"host,omitempty" yaml:"host,omitempty"`

	// Port to connect to
	Port int `json:"port" yaml:"port"`

	// Command to execute for exec probe
	Command []string `json:"command,omitempty" yaml:"command,omitempty"`

	// Initial delay seconds before starting checks
	InitialDelaySeconds int `json:"initialDelaySeconds,omitempty" yaml:"initialDelaySeconds,omitempty"`

	// Interval between checks in seconds
	IntervalSeconds int `json:"intervalSeconds,omitempty" yaml:"intervalSeconds,omitempty"`

	// Timeout for the probe in seconds
	TimeoutSeconds int `json:"timeoutSeconds,omitempty" yaml:"timeoutSeconds,omitempty"`

	// Failure threshold for the probe
	FailureThreshold int `json:"failureThreshold,omitempty" yaml:"failureThreshold,omitempty"`

	// Success threshold for the probe
	SuccessThreshold int `json:"successThreshold,omitempty" yaml:"successThreshold,omitempty"`
}

Probe represents a health check probe configuration.

func (*Probe) Validate

func (p *Probe) Validate() error

Validate validates the probe configuration.

type ProcessSecurityContext

type ProcessSecurityContext struct {
	// User to run as
	User string `json:"user,omitempty" yaml:"user,omitempty"`

	// Group to run as
	Group string `json:"group,omitempty" yaml:"group,omitempty"`

	// Run with read-only filesystem
	ReadOnlyFS bool `json:"readOnlyFS,omitempty" yaml:"readOnlyFS,omitempty"`

	// Linux capabilities to add
	Capabilities []string `json:"capabilities,omitempty" yaml:"capabilities,omitempty"`

	// Allowed syscalls (seccomp)
	AllowedSyscalls []string `json:"allowedSyscalls,omitempty" yaml:"allowedSyscalls,omitempty"`

	// Denied syscalls (seccomp)
	DeniedSyscalls []string `json:"deniedSyscalls,omitempty" yaml:"deniedSyscalls,omitempty"`
}

ProcessSecurityContext defines security settings for a process

type ProcessSpec

type ProcessSpec struct {
	// Command to run
	Command string `json:"command" yaml:"command"`

	// Command arguments
	Args []string `json:"args,omitempty" yaml:"args,omitempty"`

	// Working directory for the process
	WorkingDir string `json:"workingDir,omitempty" yaml:"workingDir,omitempty"`

	// Security settings
	SecurityContext *ProcessSecurityContext `json:"securityContext,omitempty" yaml:"securityContext,omitempty"`
}

ProcessSpec defines how to run a service as a process

func (*ProcessSpec) Validate

func (p *ProcessSpec) Validate() error

Validate validates the process specification

type ReclaimPolicy

type ReclaimPolicy string

ReclaimPolicy controls what happens to the underlying storage when the owning Volume (or owning Service for claimTemplate-created volumes) is deleted. See RUNE-069 §7 for trigger semantics; reclaim never fires on instance death.

const (
	// ReclaimPolicyRetain leaves the underlying storage in place; the Volume
	// resource is removed but data is preserved for manual recovery.
	ReclaimPolicyRetain ReclaimPolicy = "retain"
	// ReclaimPolicyDelete asks the driver to destroy the underlying storage
	// when the Volume is reclaimed.
	ReclaimPolicyDelete ReclaimPolicy = "delete"
)

type RegistryAuth

type RegistryAuth struct {
	Type     string `json:"type,omitempty" yaml:"type,omitempty"` // basic | token | ecr
	Username string `json:"username,omitempty" yaml:"username,omitempty"`
	Password string `json:"password,omitempty" yaml:"password,omitempty"`
	Token    string `json:"token,omitempty" yaml:"token,omitempty"`
	Region   string `json:"region,omitempty" yaml:"region,omitempty"`
}

RegistryAuth defines supported inline auth types

type Release

type Release struct {
	// ID is a stable unique identifier for the release.
	ID string `json:"id" yaml:"id"`

	// Name is unique within the home namespace. Equals the --release value,
	// defaulting to the runeset manifest name, then the file/dir base name.
	Name string `json:"name" yaml:"name"`

	// Namespace is the release's home namespace.
	Namespace string `json:"namespace" yaml:"namespace"`

	// Status is the current lifecycle state of the release.
	Status ReleaseStatus `json:"status" yaml:"status"`

	// Revision increments on every successful cast of this release.
	Revision int `json:"revision" yaml:"revision"`

	// Source records where the runeset came from (dir, tgz, github, url) plus
	// the ref/digest, so a revision is reproducible.
	Source ReleaseSource `json:"source" yaml:"source"`

	// Manifest is the runeset.yaml that was deployed for this revision.
	Manifest RunesetManifest `json:"manifest" yaml:"manifest"`

	// Values is the fully-merged value set used to render this revision, kept
	// for diff and rollback.
	Values map[string]interface{} `json:"values,omitempty" yaml:"values,omitempty"`

	// RenderedDigest is a checksum of the rendered castfile set, used as the
	// baseline for drift detection.
	RenderedDigest string `json:"renderedDigest,omitempty" yaml:"renderedDigest,omitempty"`

	// Owns is the authoritative set of resources this revision owns.
	Owns []OwnerRef `json:"owns,omitempty" yaml:"owns,omitempty"`

	// References records shared/cluster-scoped resources this release depends on
	// but does NOT own (and will never delete) — e.g. a pre-existing StorageClass
	// or Namespace it did not create (Decision D2).
	References []OwnerRef `json:"references,omitempty" yaml:"references,omitempty"`

	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Release is the stateful record of what a `rune cast` installed. It is the source of truth for a runeset deployment: which resources it owns, the revision history, and the merged values used — enabling list, diff, upgrade-with-prune, rollback, and clean uninstall.

Design: _docs/plugins/RUNESET_STATEFUL_RELEASES.md

A Release is namespace-scoped (its "home" namespace) but its OwnerRefs may point into other namespaces (Decision D1). A release owns only the resources it created; inherently-shared cluster-scoped kinds (StorageClass, Namespace) are referenced, not owned (Decision D2).

type ReleaseSource

type ReleaseSource struct {
	// Type mirrors RunesetSourceType (directory, package-archive, github, ...).
	Type RunesetSourceType `json:"type" yaml:"type"`
	// Location is the raw source argument (path, URL, or github shorthand).
	Location string `json:"location" yaml:"location"`
	// Ref is the resolved version reference where applicable (git ref, tag).
	Ref string `json:"ref,omitempty" yaml:"ref,omitempty"`
	// Digest is the archive/content checksum where available.
	Digest string `json:"digest,omitempty" yaml:"digest,omitempty"`
}

ReleaseSource records the provenance of a runeset deployment.

type ReleaseStatus

type ReleaseStatus string

ReleaseStatus is the lifecycle state of a Release.

const (
	// ReleaseStatusPending — intent recorded, apply in progress.
	ReleaseStatusPending ReleaseStatus = "pending"
	// ReleaseStatusDeployed — the current live revision.
	ReleaseStatusDeployed ReleaseStatus = "deployed"
	// ReleaseStatusSuperseded — a prior revision replaced by a newer one.
	ReleaseStatusSuperseded ReleaseStatus = "superseded"
	// ReleaseStatusFailed — an apply failed; prior deployed revision left live.
	ReleaseStatusFailed ReleaseStatus = "failed"
	// ReleaseStatusUninstalling — uninstall in progress.
	ReleaseStatusUninstalling ReleaseStatus = "uninstalling"
	// ReleaseStatusUninstalled — soft tombstone retained after uninstall (D4).
	ReleaseStatusUninstalled ReleaseStatus = "uninstalled"
)

type ResolvedConfigmapMount

type ResolvedConfigmapMount struct {
	// Name of the mount (for identification)
	Name string `json:"name" yaml:"name"`

	// Path where the config should be mounted
	MountPath string `json:"mountPath" yaml:"mountPath"`

	// Resolved config data (key -> value)
	Data map[string]string `json:"data" yaml:"data"`

	// Optional: specific keys to project from the config
	Items []KeyToPath `json:"items,omitempty" yaml:"items,omitempty"`
}

ResolvedConfigmapMount contains the resolved config data for mounting

type ResolvedSecretMount

type ResolvedSecretMount struct {
	// Name of the mount (for identification)
	Name string `json:"name" yaml:"name"`

	// Path where the secret should be mounted
	MountPath string `json:"mountPath" yaml:"mountPath"`

	// Resolved secret data (key -> value)
	Data map[string]string `json:"data" yaml:"data"`

	// Optional: specific keys to project from the secret
	Items []KeyToPath `json:"items,omitempty" yaml:"items,omitempty"`
}

ResolvedSecretMount contains the resolved secret data for mounting

type ResolvedVolumeMount

type ResolvedVolumeMount struct {
	// Name is the mount's service-local identifier (matches
	// Service.VolumeMount.Name).
	Name string `json:"name" yaml:"name"`

	// MountPath is the absolute container path the volume is mounted at.
	MountPath string `json:"mountPath" yaml:"mountPath"`

	// Source is the host-side path to bind into the container.
	Source string `json:"source" yaml:"source"`

	// VolumeName is the name of the bound Volume resource (in the same
	// namespace as the owning service unless the mount used an FQDN).
	VolumeName string `json:"volumeName" yaml:"volumeName"`

	// VolumeNamespace is the namespace of the bound Volume.
	VolumeNamespace string `json:"volumeNamespace,omitempty" yaml:"volumeNamespace,omitempty"`

	// ReadOnly mounts the volume read-only inside the container.
	ReadOnly bool `json:"readOnly,omitempty" yaml:"readOnly,omitempty"`

	// SubPath, if non-empty, selects a sub-path within the volume.
	SubPath string `json:"subPath,omitempty" yaml:"subPath,omitempty"`
}

ResolvedVolumeMount is the runner-facing representation of a Service VolumeMount after the orchestrator has resolved the underlying Volume to a concrete host-side source path.

Source is whatever the storage driver's Mount step produced — for the in-tree "local" driver that's the managed directory under localVolumeRoot; for "local-host" it's the operator-declared host path; for cloud block-device drivers it would be the agent's per-volume mount target under /var/lib/rune/mounts/<volume-id>/.

type Resource

type Resource interface {
	// String returns a unique identifier for the resource
	String() string

	// Equals checks if two resources are functionally equivalent
	Equals(other Resource) bool
}

Resource is a generic interface that all resources must implement

type ResourceConfig

type ResourceConfig struct {
	CPU    *CPUConfig    `yaml:"cpu,omitempty"`
	Memory *MemoryConfig `yaml:"memory,omitempty"`
}

ResourceConfig represents resource limits and requests

type ResourceLimit

type ResourceLimit struct {
	// Requested resources (guaranteed)
	Request string `json:"request,omitempty" yaml:"request,omitempty"`

	// Maximum resources (limit)
	Limit string `json:"limit,omitempty" yaml:"limit,omitempty"`
}

ResourceLimit defines request and limit for a resource.

type ResourceRef

type ResourceRef struct {
	Type      ResourceType
	Namespace string
	Name      string
	ID        string
	Key       string
}

ResourceRef is a canonical reference for resources with strongly-typed fields. Name form: rune://<type>/<namespace>/<name>/<key> ID form: rune://<type>/<namespace>/id/<id>/<key> FQDN form: <type>:<name>.<namespace>.rune[/key] Minimal form: <type>:<name>[/key] Bare form: <name> — Type and Namespace come from caller context;

accepted via ParseResourceRefWithDefaults only.

func ParseResourceRef

func ParseResourceRef(s string) (ResourceRef, error)

ParseResourceRef parses a reference and returns a ResourceRef.

func ParseResourceRefWithDefaultNamespace

func ParseResourceRefWithDefaultNamespace(s, defaultNamespace string) (ResourceRef, error)

func ParseResourceRefWithDefaults

func ParseResourceRefWithDefaults(s string, defaultType ResourceType, defaultNamespace string) (ResourceRef, error)

ParseResourceRefWithDefaults parses s as a ResourceRef and fills in defaultType / defaultNamespace for fields the input does not specify.

In addition to the canonical forms, two operator-friendly shorthands are accepted in *typed* contexts (callers supplying defaultType):

  • Bare name: "tls-smoke" → defaultType + defaultNamespace
  • NS/name shorthand: "shared/tls-smoke" → defaultType + explicit namespace

Both keep the call-site terse for the common "name in this/another namespace" case without forcing operators to type the canonical "secret:name.namespace.rune" form.

A "name" with two or more "/" is still rejected — those almost certainly indicate a confused subPath or similar typo.

An empty defaultType is allowed; the resulting ResourceRef simply has an empty Type for callers that don't care. (The NS/name shorthand is also accepted when defaultType is empty, since the shorthand carries no type information of its own.)

func (ResourceRef) HasKey

func (r ResourceRef) HasKey() bool

func (ResourceRef) IsByID

func (r ResourceRef) IsByID() bool

func (ResourceRef) IsNameRef

func (r ResourceRef) IsNameRef() bool

func (ResourceRef) ToFetchRef

func (r ResourceRef) ToFetchRef() string

func (ResourceRef) ToURI

func (r ResourceRef) ToURI() string

func (ResourceRef) WithDefaultNamespace

func (r ResourceRef) WithDefaultNamespace(ns string) ResourceRef

type ResourceType

type ResourceType string

ResourceType is the type of resource.

const (
	// ResourceTypeService is the resource type for services.
	ResourceTypeService ResourceType = "service"

	// ResourceTypeInstance is the resource type for instances.
	ResourceTypeInstance ResourceType = "instance"

	// ResourceTypeNamespace is the resource type for namespaces.
	ResourceTypeNamespace ResourceType = "namespace"

	// ResourceTypeScalingOperation is the resource type for scaling operations.
	ResourceTypeScalingOperation ResourceType = "scaling_operation"

	// ResourceTypeDeletionOperation is the resource type for deletion operations.
	ResourceTypeDeletionOperation ResourceType = "deletion_operation"

	// ResourceTypeSecret represents secrets (encrypted at rest)
	ResourceTypeSecret ResourceType = "secret"

	// ResourceTypeConfigmap represents non-sensitive configs
	ResourceTypeConfigmap ResourceType = "configmap"

	// ResourceTypeUser represents user identities
	ResourceTypeUser ResourceType = "user"

	// ResourceTypeToken represents authentication tokens
	ResourceTypeToken ResourceType = "token"

	// ResourceTypePolicy represents authorization policies
	ResourceTypePolicy ResourceType = "policy"

	// ResourceTypeAuditEvent represents append-only audit events.
	ResourceTypeAuditEvent ResourceType = "audit_event"

	// ResourceTypeVolume represents persistent volumes (RUNE-069).
	ResourceTypeVolume ResourceType = "volume"

	// ResourceTypeStorageClass represents cluster-scoped storage classes (RUNE-073).
	ResourceTypeStorageClass ResourceType = "storage_class"

	// ResourceTypeSnapshot represents volume snapshots (RUNE-071).
	ResourceTypeSnapshot ResourceType = "snapshot"

	// ResourceTypeRelease represents a stateful runeset release: the tracked,
	// revisioned record of what a `rune cast` installed, used for list / diff /
	// rollback / clean uninstall. See _docs/plugins/RUNESET_STATEFUL_RELEASES.md.
	ResourceTypeRelease ResourceType = "release"

	// ResourceTypeSavedView represents a cluster-scoped RuneSight saved view
	// (a named Log Explorer query: LogQL + relative time range).
	ResourceTypeSavedView ResourceType = "saved_view"

	// ResourceTypeAlertRule represents a cluster-scoped RuneSight alert rule
	// (a LogQL count threshold evaluated by the runed alerter).
	ResourceTypeAlertRule ResourceType = "alert_rule"

	// ResourceTypeChannel represents a cluster-scoped notification channel
	// (templated webhook / slack) referenced by alert rules.
	ResourceTypeChannel ResourceType = "channel"
)

type Resources

type Resources struct {
	// CPU request in millicores (1000m = 1 CPU)
	CPU ResourceLimit `json:"cpu,omitempty" yaml:"cpu,omitempty"`

	// Memory request in bytes
	Memory ResourceLimit `json:"memory,omitempty" yaml:"memory,omitempty"`
}

Resources represents resource requirements for a service instance.

type RestartPolicy

type RestartPolicy string

RestartPolicy defines how instances should be restarted

const (
	// RestartPolicyAlways means always restart when not explicitly stopped
	RestartPolicyAlways RestartPolicy = "Always"

	// RestartPolicyOnFailure means only restart on failure
	RestartPolicyOnFailure RestartPolicy = "OnFailure"

	// RestartPolicyNever means never restart automatically, only manual restarts are allowed
	RestartPolicyNever RestartPolicy = "Never"
)

type RetryPolicy

type RetryPolicy struct {
	// Number of retry attempts
	Count int `json:"count" yaml:"count"`

	// Backoff type (fixed or exponential)
	Backoff string `json:"backoff" yaml:"backoff"`

	// Initial backoff duration in seconds (for fixed or exponential)
	BackoffSeconds int `json:"backoffSeconds,omitempty" yaml:"backoffSeconds,omitempty"`
}

RetryPolicy defines when and how to retry failed jobs.

type RotationAction

type RotationAction struct {
	// Services to reload (send SIGHUP)
	ReloadServices []string `json:"reloadServices,omitempty" yaml:"reloadServices,omitempty"`

	// Services to restart (rolling restart)
	RestartServices []string `json:"restartServices,omitempty" yaml:"restartServices,omitempty"`

	// Job to run
	RunJob string `json:"runJob,omitempty" yaml:"runJob,omitempty"`
}

RotationAction defines an action to take after secret rotation.

type RotationPolicy

type RotationPolicy struct {
	// Interval between rotations (e.g., "30d", "90d")
	Interval string `json:"interval" yaml:"interval"`

	// Actions to take after rotation
	OnRotate []RotationAction `json:"onRotate,omitempty" yaml:"onRotate,omitempty"`
}

RotationPolicy defines when and how to rotate a secret.

type Route

type Route struct {
	// Unique identifier for the route
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the route
	Name string `json:"name" yaml:"name"`

	// Namespace the route belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Gateway this route is attached to
	Gateway string `json:"gateway" yaml:"gateway"`

	// Host or hosts this route matches (e.g., "api.example.com")
	Hosts []string `json:"hosts,omitempty" yaml:"hosts,omitempty"`

	// HTTP path-based routing rules
	HTTP []HTTPRoute `json:"http,omitempty" yaml:"http,omitempty"`

	// TCP routing rules (port-based)
	TCP []TCPRoute `json:"tcp,omitempty" yaml:"tcp,omitempty"`

	// Priority of this route (higher numbers take precedence)
	Priority int `json:"priority,omitempty" yaml:"priority,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Route represents a rule for routing traffic from a gateway to services.

type RouteDestination

type RouteDestination struct {
	// Service name to route to
	Service string `json:"service" yaml:"service"`

	// Namespace of the service (optional, defaults to route's namespace)
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

	// Port on the service to route to
	Port int `json:"port" yaml:"port"`

	// Weight for traffic splitting (0-100)
	Weight int `json:"weight,omitempty" yaml:"weight,omitempty"`

	// Subset of the service to route to (requires service to have defined subsets)
	Subset string `json:"subset,omitempty" yaml:"subset,omitempty"`
}

RouteDestination represents the target of a route.

type RouteSpec

type RouteSpec struct {
	// Route metadata and rules
	Route struct {
		// Human-readable name for the route (required)
		Name string `json:"name" yaml:"name"`

		// Namespace the route belongs to (optional, defaults to "default")
		Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

		// Gateway this route is attached to
		Gateway string `json:"gateway" yaml:"gateway"`

		// Host or hosts this route matches
		Hosts []string `json:"hosts,omitempty" yaml:"hosts,omitempty"`

		// HTTP path-based routing rules
		HTTP []HTTPRoute `json:"http,omitempty" yaml:"http,omitempty"`

		// TCP routing rules (port-based)
		TCP []TCPRoute `json:"tcp,omitempty" yaml:"tcp,omitempty"`

		// Priority of this route (higher numbers take precedence)
		Priority int `json:"priority,omitempty" yaml:"priority,omitempty"`
	} `json:"route" yaml:"route"`
}

RouteSpec represents the YAML specification for a route.

func (*RouteSpec) ToRoute

func (r *RouteSpec) ToRoute() (*Route, error)

ToRoute converts a RouteSpec to a Route.

func (*RouteSpec) Validate

func (r *RouteSpec) Validate() error

Validate checks if a route specification is valid.

type RunIf

type RunIf struct {
	// Type selects the predicate. Empty is treated as RunIfFreshVolume.
	Type RunIfType `json:"type,omitempty" yaml:"type,omitempty"`

	// Path is the absolute in-container path tested when
	// Type=fileMissing. Required iff Type=fileMissing.
	Path string `json:"path,omitempty" yaml:"path,omitempty"`

	// Volume optionally restricts a fileMissing check to one named
	// parent volume. When empty, any mounted parent volume that
	// contains the path counts.
	Volume string `json:"volume,omitempty" yaml:"volume,omitempty"`
}

RunIf encodes the predicate that decides whether an InitStep runs on a given instance start. Validated by Service.Validate.

type RunIfType

type RunIfType string

RunIfType selects when an InitStep should execute. See RUNE-121 §3 for the rationale.

const (
	// RunIfFreshVolume is the default: the step runs only when the
	// parent volume(s) have not been successfully initialised for the
	// owning service before. Anchored on
	// Volume.Status.InitializedFor[serviceID].
	RunIfFreshVolume RunIfType = "freshVolume"

	// RunIfFileMissing runs the step only when RunIf.Path does not
	// exist inside the parent volume(s).
	RunIfFileMissing RunIfType = "fileMissing"

	// RunIfAlways runs the step on every instance start.
	RunIfAlways RunIfType = "always"
)

type RuneFile

type RuneFile struct {
	// Server configuration
	Server *ServerConfig `yaml:"server,omitempty"`

	// Data directory for persistent storage
	DataDir string `yaml:"data_dir,omitempty"`

	// Client configuration
	Client *ClientConfig `yaml:"client,omitempty"`

	// Docker runner configuration (including private registries)
	Docker *DockerConfig `yaml:"docker,omitempty"`

	// Default namespace
	Namespace string `yaml:"namespace,omitempty"`

	// Authentication configuration
	Auth *AuthConfig `yaml:"auth,omitempty"`

	// Resource limits and requests
	Resources *ResourceConfig `yaml:"resources,omitempty"`

	// Logging configuration
	Log *LogConfig `yaml:"log,omitempty"`

	// Secret encryption + limits configuration
	Secret *SecretConfig `yaml:"secret,omitempty"`

	// Top-level config-resource limits (RUNE-016)
	Config *ConfigResourceConfig `yaml:"config,omitempty"`

	// Plugin configuration
	Plugins *PluginConfig `yaml:"plugins,omitempty"`

	// Networking layer (RUNE-040..067)
	Networking *NetworkingConfig `yaml:"networking,omitempty"`

	// Telemetry / metrics
	Telemetry *TelemetryConfig `yaml:"telemetry,omitempty"`

	// Node placement (edge / worker / leader)
	Node *NodeConfig `yaml:"node,omitempty"`

	// Ingress (edge node terminating user traffic)
	Ingress *IngressConfig `yaml:"ingress,omitempty"`

	// ACME (Let's Encrypt) configuration
	ACME *ACMEConfig `yaml:"acme,omitempty"`

	// Storage drivers. Per-driver opaque config maps keyed
	// by registry name (e.g. "local", "local-host"). The shape of
	// each inner map is driver-specific; the loader keeps it as raw
	// `any` and hands it to the driver factory.
	Storage *StorageConfig `yaml:"storage,omitempty"`

	// FailedInstanceRetention bounds how long preserved Failed-instance
	// containers (tombstones) survive before the reconciler's retention
	// GC reaps them. Mirrors internal/config.FailedInstanceRetention.
	FailedInstanceRetention *FailedInstanceRetentionConfig `yaml:"failed_instance_retention,omitempty"`

	// UI configures the embedded web dashboard (RUNE-200). Mirrors
	// internal/config.UI.
	UI *UIConfig `yaml:"ui,omitempty"`

	// Observability configures the native observability subsystem
	// (RuneSight): the agent forwarder, the log store backend, and
	// retention. Mirrors internal/config.Observability. When absent or
	// disabled, runed forwards no logs and `rune logs` falls back to the
	// live ephemeral stream.
	Observability *ObservabilityConfig `yaml:"observability,omitempty"`
	// contains filtered or unexported fields
}

RuneFile represents a Rune configuration file.

MUST stay shape-compatible with internal/config.Config — runed loads the runefile via viper into Config; lint loads it here. The two structs are kept parallel by hand and policed by a reflection-based parity test (see runefile_parity_test.go, RUNE-112). When you add a field to one, add it to the other (and to isKnownField below).

func ParseRuneFile

func ParseRuneFile(filePath string) (*RuneFile, error)

ParseRuneFile parses a Rune configuration file from the given file path. Both YAML and TOML are accepted (TOML is detected via the `.toml` extension and transcoded to YAML before parsing — see readRunefileBytes for the rationale). Line numbers reported by the linter for TOML files refer to positions in the post-transcode YAML, not the original TOML source; callers that care about original-file positions should fall back to printing the key name only.

func (*RuneFile) GetLineInfo

func (rf *RuneFile) GetLineInfo(key string) (int, bool)

GetLineInfo returns the line number for a given key

func (*RuneFile) GetName

func (rf *RuneFile) GetName() string

func (*RuneFile) Lint

func (rf *RuneFile) Lint() []error

Lint performs validation and returns a list of errors with line numbers

func (*RuneFile) Validate

func (rf *RuneFile) Validate() error

Validate validates the RuneFile configuration

type RunesetContext

type RunesetContext struct {
	Namespace   string
	Mode        string
	ReleaseName string
	Runeset     RunesetManifest
}

func (RunesetContext) GetValues

func (ctx RunesetContext) GetValues() map[string]interface{}

type RunesetManifest

type RunesetManifest struct {
	Name        string                 `yaml:"name"`
	Version     string                 `yaml:"version"`
	Description string                 `yaml:"description"`
	Namespace   string                 `yaml:"namespace"`
	Defaults    map[string]interface{} `yaml:"defaults"`
}

func ParseRunesetManifest

func ParseRunesetManifest(manifestPath string) (RunesetManifest, error)

ParseRunesetManifest reads and parses a runeset manifest YAML file.

type RunesetSourceType

type RunesetSourceType string
const (
	RunesetSourceTypeDirectory      RunesetSourceType = "directory"
	RunesetSourceTypeRemoteArchive  RunesetSourceType = "remote-archive"
	RunesetSourceTypePackageArchive RunesetSourceType = "package-archive"
	RunesetSourceTypeGitHub         RunesetSourceType = "github"
	RunesetSourceTypeUnknown        RunesetSourceType = "unknown"
)

type RunnerType

type RunnerType string

RunnerType is the type of runner for an instance.

const (
	RunnerTypeTest    RunnerType = "test"
	RunnerTypeDocker  RunnerType = "docker"
	RunnerTypeProcess RunnerType = "process"
)

type RuntimeType

type RuntimeType string

Runtime types

const (
	RuntimeTypeContainer RuntimeType = "container"
	RuntimeTypeProcess   RuntimeType = "process"
)

type SavedView

type SavedView struct {
	// Unique identifier.
	ID string `json:"id" yaml:"id"`

	// DNS-1123 cluster-unique name (doubles as the URL-safe slug).
	Name string `json:"name" yaml:"name"`

	// Description is optional free-text shown in the Saved Views list.
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// LogQL is the saved query text (the Core-tier subset the ObserveService
	// parses). Stored verbatim; parsed/validated at save time so a view can
	// never hold an unparseable query.
	LogQL string `json:"logql" yaml:"logql"`

	// Range is the dashboard's relative time-range token ("15m", "1h", "24h",
	// ...). The Explorer resolves it to absolute start/end at load time so a
	// saved view is always "the last X", not a frozen window.
	Range string `json:"range,omitempty" yaml:"range,omitempty"`

	// Pinned views surface on the RuneSight home card and sort first.
	Pinned bool `json:"pinned,omitempty" yaml:"pinned,omitempty"`

	// CreatedBy attributes the view (auth principal name; informational).
	CreatedBy string `json:"createdBy,omitempty" yaml:"createdBy,omitempty"`

	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

SavedView is a named, reusable Log Explorer query: the LogQL text plus the time-range token the dashboard restores when the view is loaded. Views are cluster-scoped and shared (one list for the whole cluster, attributed via CreatedBy) — the first of the RuneSight dashboard resources (saved views, alert rules) persisted in the state store.

type ScalingMode

type ScalingMode string

ScalingMode defines how the scaling operation should be performed

const (
	// ScalingModeImmediate indicates scaling should happen immediately
	ScalingModeImmediate ScalingMode = "immediate"

	// ScalingModeGradual indicates scaling should happen gradually
	ScalingModeGradual ScalingMode = "gradual"
)

type ScalingOperation

type ScalingOperation struct {
	// Unique identifier for the operation
	ID string `json:"id"`

	// Namespace the service belongs to
	Namespace string `json:"namespace"`

	// Name of the service being scaled
	ServiceName string `json:"service_name"`

	// Current scale when operation started
	CurrentScale int `json:"current_scale"`

	// Target scale to reach
	TargetScale int `json:"target_scale"`

	// Step size for gradual scaling
	StepSize int `json:"step_size"`

	// Interval between steps in seconds
	Interval int `json:"interval"`

	// Time the operation started
	StartTime time.Time `json:"start_time"`

	// Time the operation ended (if completed/failed/cancelled)
	EndTime time.Time `json:"end_time,omitempty"`

	// Current status of the operation
	Status ScalingOperationStatus `json:"status"`

	// Mode of scaling (immediate or gradual)
	Mode ScalingMode `json:"mode"`

	// Reason for failure/cancellation if applicable
	FailureReason string `json:"failure_reason,omitempty"`
}

ScalingOperation represents a scaling operation for a service

func (*ScalingOperation) GetMetadata

func (s *ScalingOperation) GetMetadata() *ScalingOperationMetadata

GetMetadata returns the resource metadata.

type ScalingOperationMetadata

type ScalingOperationMetadata struct {
	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

ScalingOperationMetadata represents metadata for a scaling operation

type ScalingOperationParams

type ScalingOperationParams struct {
	// Current scale of the service
	CurrentScale int

	// Target scale to reach
	TargetScale int

	// Step size for gradual scaling
	StepSize int

	// Interval between steps in seconds
	IntervalSeconds int

	// Whether to use gradual scaling
	IsGradual bool
}

ScalingOperationParams encapsulates parameters for creating a scaling operation

type ScalingOperationStatus

type ScalingOperationStatus string

ScalingOperationStatus represents the status of a scaling operation

const (
	// ScalingOperationStatusInProgress indicates the operation is still running
	ScalingOperationStatusInProgress ScalingOperationStatus = "in_progress"

	// ScalingOperationStatusCompleted indicates the operation completed successfully
	ScalingOperationStatusCompleted ScalingOperationStatus = "completed"

	// ScalingOperationStatusFailed indicates the operation failed
	ScalingOperationStatusFailed ScalingOperationStatus = "failed"

	// ScalingOperationStatusCancelled indicates the operation was cancelled
	ScalingOperationStatusCancelled ScalingOperationStatus = "cancelled"
)

type SeccompProfile

type SeccompProfile struct {
	// Type selects the profile family. Empty is treated as "default".
	Type SeccompProfileType `json:"type,omitempty" yaml:"type,omitempty"`

	// LocalhostProfile is an absolute path to a JSON seccomp profile
	// on the runtime host. Required iff Type=localhost.
	LocalhostProfile string `json:"localhostProfile,omitempty" yaml:"localhostProfile,omitempty"`
}

SeccompProfile selects a seccomp policy.

type SeccompProfileType

type SeccompProfileType string

SeccompProfileType enumerates the supported seccomp profile selectors. Both Kubernetes PascalCase (Unconfined / RuntimeDefault / Localhost) and lowercase variants are accepted on input — Canonical() normalises them to the lowercase form used by switch statements internally.

const (
	// SeccompProfileDefault uses the runtime's default profile.
	// Aliases: "default", "RuntimeDefault" (the k8s name).
	SeccompProfileDefault SeccompProfileType = "default"

	// SeccompProfileUnconfined disables seccomp filtering. Admin-gated.
	// Aliases: "unconfined", "Unconfined" (the k8s name).
	SeccompProfileUnconfined SeccompProfileType = "unconfined"

	// SeccompProfileLocalhost loads a profile from a path on the host.
	// Aliases: "localhost", "Localhost" (the k8s name).
	SeccompProfileLocalhost SeccompProfileType = "localhost"
)

func (SeccompProfileType) Canonical

func (t SeccompProfileType) Canonical() SeccompProfileType

Canonical returns the lowercase, alias-resolved form of t. Used at every comparison site so a user writing PascalCase (the k8s convention, what they're most likely to copy-paste from k8s docs) gets the same behaviour as the canonical lowercase form.

type Secret

type Secret struct {
	// Unique identifier for the secret
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the secret (DNS-1123 unique name within a namespace)
	Name string `json:"name" yaml:"name"`

	// Namespace the secret belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Type of secret (static or dynamic)
	Type string `json:"type" yaml:"type"`

	// Static data (encrypted at rest, only for static secrets)
	Data map[string]string `json:"-" yaml:"-"` // Not serialized, stored encrypted separately

	// DataKeys is the sorted list of keys present in Data. It is populated
	// by metadata-only API responses (Get, List) so callers can see the
	// shape of a secret without learning its values. Reveal responses
	// populate both Data and DataKeys.
	DataKeys []string `json:"dataKeys,omitempty" yaml:"dataKeys,omitempty"`

	// Engine configuration for dynamic secrets
	Engine *SecretEngine `json:"engine,omitempty" yaml:"engine,omitempty"`

	// Rotation configuration
	Rotation *RotationPolicy `json:"rotation,omitempty" yaml:"rotation,omitempty"`

	// Current version number
	Version int `json:"version" yaml:"version"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`

	// Last rotation timestamp
	LastRotated *time.Time `json:"lastRotated,omitempty" yaml:"lastRotated,omitempty"`

	// OwnedBy is the system ownership stamp set when a runeset release manages
	// this secret. Distinct from user data; used for GC and drift detection.
	// See _docs/plugins/RUNESET_STATEFUL_RELEASES.md.
	OwnedBy *OwnedBy `json:"ownedBy,omitempty" yaml:"ownedBy,omitempty"`
}

Secret represents a securely stored piece of sensitive data.

func UnmarshalSecretPayload

func UnmarshalSecretPayload(b []byte) (*Secret, error)

UnmarshalSecretPayload decodes a secret serialized by MarshalSecretPayload, restoring the Data map that plain unmarshaling would drop.

type SecretConfig

type SecretConfig struct {
	Encryption *EncryptionConfig `yaml:"encryption,omitempty"`
	Limits     *LimitsConfig     `yaml:"limits,omitempty"`
}

SecretConfig represents secret encryption + storage limits configuration

type SecretEngine

type SecretEngine struct {
	// Name of the engine to use (references a SecretsEngine resource)
	Name string `json:"name" yaml:"name"`

	// Role or profile to use with the engine (engine-specific)
	Role string `json:"role,omitempty" yaml:"role,omitempty"`

	// Engine-specific configuration for this secret
	Config map[string]interface{} `json:"config,omitempty" yaml:"config,omitempty"`
}

SecretEngine defines a dynamic secret engine configuration.

type SecretMount

type SecretMount struct {
	// Name of the mount (for identification)
	Name string `json:"name" yaml:"name"`

	// Path where the secret should be mounted
	MountPath string `json:"mountPath" yaml:"mountPath"`

	// Name of the secret to mount
	SecretName string `json:"secretName" yaml:"secretName"`

	// Optional: specific keys to project from the secret
	Items []KeyToPath `json:"items,omitempty" yaml:"items,omitempty"`
}

SecretMount defines a secret to be mounted in a container.

type SecretSpec

type SecretSpec struct {
	// Human-readable name for the secret (required)
	Name string `json:"name" yaml:"name"`

	// Namespace the secret belongs to (optional, defaults to "default")
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

	// Type of secret (static or dynamic)
	Type string `json:"type" yaml:"type"`

	// Secret data for static secrets (only for creation, not returned in GET)
	Data map[string]string `json:"data,omitempty" yaml:"data,omitempty"`

	// Single value convenience field (alternative to data.value for simple secrets)
	Value string `json:"value,omitempty" yaml:"value,omitempty"`

	// Base64-encoded value (for binary data)
	ValueBase64 string `json:"valueBase64,omitempty" yaml:"valueBase64,omitempty"`

	// Engine configuration for dynamic secrets
	Engine *SecretEngine `json:"engine,omitempty" yaml:"engine,omitempty"`

	// Rotation configuration
	Rotation *RotationPolicy `json:"rotation,omitempty" yaml:"rotation,omitempty"`

	// Skip indicates this spec should be ignored by castfile parsing
	Skip bool `json:"skip,omitempty" yaml:"skip,omitempty"`
	// contains filtered or unexported fields
}

SecretSpec represents the YAML specification for a secret.

func (*SecretSpec) GetName

func (s *SecretSpec) GetName() string

Implement Spec interface for SecretSpec

func (*SecretSpec) GetNamespace

func (s *SecretSpec) GetNamespace() string

func (*SecretSpec) Kind

func (s *SecretSpec) Kind() string

func (*SecretSpec) RestoreTemplateReferences

func (s *SecretSpec) RestoreTemplateReferences(templateMap map[string]string)

RestoreTemplateReferences restores template references in secret data values. Called by the castfile parser so cast-time templating in `data:` values (e.g. `{{ secret:db-host/value }}`) survives YAML parsing. The literal `{{ ... }}` strings are substituted at cast time by the cast-secret renderer.

func (*SecretSpec) ToSecret

func (s *SecretSpec) ToSecret() (*Secret, error)

ToSecret converts a SecretSpec to a Secret.

func (*SecretSpec) UnmarshalYAML

func (s *SecretSpec) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements custom unmarshalling so `data` can be provided either as a mapping (key: value) or as a sequence of {key, value} objects.

func (*SecretSpec) Validate

func (s *SecretSpec) Validate() error

Validate checks if a secret specification is valid.

type SecretsEngine

type SecretsEngine struct {
	// Unique identifier for the engine
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the engine
	Name string `json:"name" yaml:"name"`

	// Namespace the engine belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Type of engine (builtin, function, plugin)
	Type string `json:"type" yaml:"type"`

	// For function-based engines, the reference to the function
	Function string `json:"function,omitempty" yaml:"function,omitempty"`

	// For plugin-based engines, the path to the plugin executable
	Path string `json:"path,omitempty" yaml:"path,omitempty"`

	// Engine-wide configuration
	Config map[string]interface{} `json:"config,omitempty" yaml:"config,omitempty"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

SecretsEngine represents a configured secrets engine.

type SecretsEngineSpec

type SecretsEngineSpec struct {
	// Engine metadata and configuration
	SecretsEngine struct {
		// Human-readable name for the engine (required)
		Name string `json:"name" yaml:"name"`

		// Namespace the engine belongs to (optional, defaults to "default")
		Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

		// Type of engine (required: builtin, function, plugin)
		Type string `json:"type" yaml:"type"`

		// For function-based engines, the reference to the function
		Function string `json:"function,omitempty" yaml:"function,omitempty"`

		// For plugin-based engines, the path to the plugin executable
		Path string `json:"path,omitempty" yaml:"path,omitempty"`

		// Engine-wide configuration
		Config map[string]interface{} `json:"config,omitempty" yaml:"config,omitempty"`
	} `json:"secretsEngine" yaml:"secretsEngine"`
}

SecretsEngineSpec represents the YAML specification for a secrets engine.

func (*SecretsEngineSpec) ToSecretsEngine

func (s *SecretsEngineSpec) ToSecretsEngine() (*SecretsEngine, error)

ToSecretsEngine converts a SecretsEngineSpec to a SecretsEngine.

func (*SecretsEngineSpec) Validate

func (s *SecretsEngineSpec) Validate() error

Validate checks if a secrets engine specification is valid.

type SecurityContext

type SecurityContext struct {
	// SeccompProfile selects the seccomp policy applied to the
	// container. Nil means the runtime default profile.
	SeccompProfile *SeccompProfile `json:"seccompProfile,omitempty" yaml:"seccompProfile,omitempty"`

	// CapAdd are Linux capabilities granted to the container in
	// addition to the runtime defaults (e.g. "SYS_ADMIN", "NET_ADMIN").
	CapAdd []string `json:"capAdd,omitempty" yaml:"capAdd,omitempty"`

	// CapDrop are Linux capabilities removed from the container,
	// applied after CapAdd.
	CapDrop []string `json:"capDrop,omitempty" yaml:"capDrop,omitempty"`

	// Privileged grants full access to host devices and namespaces.
	// Admin-gated by the services.privileged policy verb.
	Privileged bool `json:"privileged,omitempty" yaml:"privileged,omitempty"`
}

SecurityContext bundles container-level security knobs surfaced to users. Mirrors generated.SecurityContext on the wire and is also allowed on Service for the main container.

func (*SecurityContext) RequiresPrivilegedGate

func (sc *SecurityContext) RequiresPrivilegedGate() bool

RequiresPrivilegedGate reports whether this SecurityContext contains fields that the server should reject for callers without the services.privileged policy verb.

func (*SecurityContext) Validate

func (sc *SecurityContext) Validate() error

Validate checks structural invariants on SecurityContext. It does not enforce policy gates (those are checked server-side via RBAC).

type ServerConfig

type ServerConfig struct {
	GRPCAddress string     `yaml:"grpc_address,omitempty"`
	HTTPAddress string     `yaml:"http_address,omitempty"`
	TLS         *TLSConfig `yaml:"tls,omitempty"`
}

ServerConfig represents server endpoint configuration

type Service

type Service struct {
	NamespacedResource `json:"-" yaml:"-"`

	// Unique identifier for the service
	ID string `json:"id" yaml:"id"`

	// Human-readable name for the service // DNS-1123 unique name within a namespace
	Name string `json:"name" yaml:"name"`

	// Namespace the service belongs to
	Namespace string `json:"namespace" yaml:"namespace"`

	// Labels are key/value pairs that can be used to organize and categorize services
	Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

	// Container image for the service
	Image string `json:"image,omitempty" yaml:"image,omitempty"`

	// Named registry selector for pulling the image (optional)
	ImageRegistry string `json:"imageRegistry,omitempty" yaml:"imageRegistry,omitempty"`

	// Registry override allowing inline auth or named selection (optional)
	Registry *ServiceRegistryOverride `json:"registry,omitempty" yaml:"registry,omitempty"`

	// ImagePull controls when the runner pulls the container image.
	// Allowed values: "always", "missing", "never". Empty defaults to
	// "always" (re-pull on every deploy/restart).
	ImagePull string `json:"imagePull,omitempty" yaml:"imagePull,omitempty"`

	// Command to run in the container (overrides image CMD)
	Command string `json:"command,omitempty" yaml:"command,omitempty"`

	// Arguments to the command
	Args []string `json:"args,omitempty" yaml:"args,omitempty"`

	// Environment variables for the service
	Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`

	// Imported environment variables sources (normalized from spec)
	EnvFrom []EnvFromSource `json:"envFrom,omitempty" yaml:"envFrom,omitempty"`

	// Number of instances to run
	Scale int `json:"scale" yaml:"scale"`

	// Ports exposed by the service
	Ports []ServicePort `json:"ports,omitempty" yaml:"ports,omitempty"`

	// Resource requirements for each instance
	Resources Resources `json:"resources,omitempty" yaml:"resources,omitempty"`

	// Health checks for the service
	Health *HealthCheck `json:"health,omitempty" yaml:"health,omitempty"`

	// Network policy for controlling traffic
	NetworkPolicy *ServiceNetworkPolicy `json:"networkPolicy,omitempty" yaml:"networkPolicy,omitempty"`

	// External exposure configuration
	Expose *ServiceExpose `json:"expose,omitempty" yaml:"expose,omitempty"`

	// Placement preferences and requirements
	Affinity *ServiceAffinity `json:"affinity,omitempty" yaml:"affinity,omitempty"`

	// Autoscaling configuration
	Autoscale *ServiceAutoscale `json:"autoscale,omitempty" yaml:"autoscale,omitempty"`

	// Secret mounts
	SecretMounts []SecretMount `json:"secretMounts,omitempty" yaml:"secretMounts,omitempty"`

	// Config mounts
	ConfigmapMounts []ConfigmapMount `json:"configmapMounts,omitempty" yaml:"configmapMounts,omitempty"`

	// Volume mounts. Each entry references either a pre-existing
	// VolumeClaim by name (Claim) or an inline ClaimTemplate that the
	// VolumeController materializes into a per-instance Volume.
	Volumes []VolumeMount `json:"volumes,omitempty" yaml:"volumes,omitempty"`

	// InitSteps run sequentially before each instance's main
	// container starts. They share the parent's volumes / secret /
	// config / env by default. See RUNE-121.
	InitSteps []InitStep `json:"initSteps,omitempty" yaml:"initSteps,omitempty"`

	// SecurityContext applied to the main container. Privileged=true
	// and seccompProfile.type=unconfined are gated server-side behind
	// the services.privileged policy verb.
	SecurityContext *SecurityContext `json:"securityContext,omitempty" yaml:"securityContext,omitempty"`

	// Service discovery configuration
	Discovery *ServiceDiscovery `json:"discovery,omitempty" yaml:"discovery,omitempty"`

	// Dependencies this service declares (normalized internal form)
	Dependencies []DependencyRef `json:"dependencies,omitempty" yaml:"dependencies,omitempty"`

	// Status of the service
	Status ServiceStatus `json:"status" yaml:"status"`

	// StatusReason is a short, machine-friendly slug describing why
	// the service is in its current Status. Set by the reconciler when
	// rolling up the worst instance state. Examples: "ImageUnreachable",
	// "Unhealthy", "OutOfMemory", "Unplaceable", "ConfigMissing".
	// Empty when Status is Running.
	StatusReason string `json:"statusReason,omitempty" yaml:"statusReason,omitempty"`

	// StatusMessage is a single human-readable sentence explaining
	// StatusReason, copied verbatim from the worst instance's
	// StatusMessage. The CLI shows this directly on `rune get
	// service <name>` and on cast failure so developers never have to
	// run a second command to learn why a service is unhealthy.
	StatusMessage string `json:"statusMessage,omitempty" yaml:"statusMessage,omitempty"`

	// IngressCert tracks asynchronous TLS certificate state for the
	// ingress controller (RUNE-066). Populated only when Expose is
	// configured for ACME-managed TLS. The orchestrator updates this
	// field independently of cast; cast does not block on issuance.
	IngressCert *IngressCertStatus `json:"ingressCert,omitempty" yaml:"ingressCert,omitempty"`

	// Instances of this service currently running
	Instances []Instance `json:"instances,omitempty" yaml:"instances,omitempty"`

	// Runtime for the service ("container" or "process")
	Runtime RuntimeType `json:"runtime,omitempty" yaml:"runtime,omitempty"`

	// Process-specific configuration (when Runtime="process")
	Process *ProcessSpec `json:"process,omitempty" yaml:"process,omitempty"`

	// Restart policy for the service
	RestartPolicy RestartPolicy `json:"restart_policy,omitempty" yaml:"restart_policy,omitempty"`

	// Metadata for the service
	Metadata *ServiceMetadata `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}

Service represents a deployable application or workload.

func (*Service) CalculateHash

func (s *Service) CalculateHash() string

CalculateHash generates a hash of service properties that should trigger reconciliation when changed

func (*Service) Equals

func (s *Service) Equals(other Resource) bool

Equals checks if two services are functionally equivalent for watch purposes

func (*Service) GetResourceType

func (s *Service) GetResourceType() ResourceType

func (*Service) String

func (s *Service) String() string

String returns a unique identifier for the service

func (*Service) Validate

func (s *Service) Validate() error

Validate validates the service configuration.

type ServiceAffinity

type ServiceAffinity struct {
	// Hard constraints (service can only run on nodes matching these)
	Required []string `json:"required,omitempty" yaml:"required,omitempty"`

	// Soft preferences (scheduler will try to place on nodes matching these)
	Preferred []string `json:"preferred,omitempty" yaml:"preferred,omitempty"`

	// Run instances near services matching these labels
	With []string `json:"with,omitempty" yaml:"with,omitempty"`

	// Avoid running instances on nodes with services matching these labels
	Avoid []string `json:"avoid,omitempty" yaml:"avoid,omitempty"`

	// Try to distribute instances across this topology key (e.g., "zone")
	Spread string `json:"spread,omitempty" yaml:"spread,omitempty"`
}

ServiceAffinity defines placement rules for a service.

type ServiceAutoscale

type ServiceAutoscale struct {
	// Whether autoscaling is enabled
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Minimum number of instances
	Min int `json:"min" yaml:"min"`

	// Maximum number of instances
	Max int `json:"max" yaml:"max"`

	// Metric to scale on (e.g., cpu, memory)
	Metric string `json:"metric" yaml:"metric"`

	// Target value for the metric (e.g., 70%)
	Target string `json:"target" yaml:"target"`

	// Cooldown period between scaling events
	Cooldown string `json:"cooldown,omitempty" yaml:"cooldown,omitempty"`

	// Maximum number of instances to add/remove in a single scaling event
	Step int `json:"step,omitempty" yaml:"step,omitempty"`
}

ServiceAutoscale defines autoscaling behavior for a service.

type ServiceDependency

type ServiceDependency struct {
	// Optional raw FQDN captured by YAML parsing helpers
	FQDN string `json:"-" yaml:"-"`

	Service   string `json:"service,omitempty" yaml:"service,omitempty"`
	Secret    string `json:"secret,omitempty" yaml:"secret,omitempty"`
	Configmap string `json:"configmap,omitempty" yaml:"configmap,omitempty"`
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
}

ServiceDependency is the spec-facing dependency format. YAML supports either string FQDN or this structured form per entry.

func (*ServiceDependency) UnmarshalYAML

func (d *ServiceDependency) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML allows ServiceDependency entries to be specified as either a plain string (FQDN or resource ref) or a structured object.

type ServiceDiscovery

type ServiceDiscovery struct {
	// Discovery mode (load-balanced or headless)
	Mode string `json:"mode,omitempty" yaml:"mode,omitempty"`

	// VIP is the cluster virtual IP allocated for this service. Set by
	// the control plane on Create via the cluster VIP allocator
	// (RUNE-040). Stable for the lifetime of the service ID.
	VIP string `json:"vip,omitempty" yaml:"vip,omitempty"`

	// LocalityPreference controls how the userspace proxy picks
	// endpoints (RUNE-041). One of "" (no preference), "prefer-local"
	// (same-node first, fall back to remote), or "local-only" (fail
	// closed if no local endpoint).
	LocalityPreference string `json:"localityPreference,omitempty" yaml:"localityPreference,omitempty"`
}

ServiceDiscovery is the persisted service discovery state (API/store).

type ServiceDiscoverySpec

type ServiceDiscoverySpec struct {
	Mode               string `json:"mode,omitempty" yaml:"mode,omitempty"`
	LocalityPreference string `json:"localityPreference,omitempty" yaml:"localityPreference,omitempty"`
}

ServiceDiscoverySpec is the operator-facing discovery block in cast YAML. It intentionally has no VIP field — the control plane assigns a stable cluster VIP at service create time (RUNE-040).

type ServiceEndpoints

type ServiceEndpoints struct {
	// Service full name (namespace.name)
	ServiceID string `json:"serviceId" yaml:"serviceId"`

	// Individual endpoints (instances) for this service
	Endpoints []Endpoint `json:"endpoints" yaml:"endpoints"`

	// Service-level metadata
	Metadata map[string]string `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}

ServiceEndpoints represents the discovered endpoints for a service.

type ServiceExpose

type ServiceExpose struct {
	// Port or port name to expose
	Port string `json:"port" yaml:"port"`

	// Host for the exposed service
	Host string `json:"host,omitempty" yaml:"host,omitempty"`

	// Path prefix for the exposed service
	Path string `json:"path,omitempty" yaml:"path,omitempty"`

	// TLS configuration for the exposed service
	TLS *ExposeServiceTLS `json:"tls,omitempty" yaml:"tls,omitempty"`

	// AllowCIDRs restricts inbound connections to these source CIDRs,
	// enforced at the ingress listener against the real TCP peer (not a
	// forwarding header). Empty means "no restriction" (allow all) — never
	// deny-all. Defense-in-depth for origin lockdown behind a CDN. Only
	// meaningful when ingress is the direct TCP terminator (no L4 LB in
	// front rewriting the source IP).
	AllowCIDRs []string `json:"allowCidrs,omitempty" yaml:"allowCidrs,omitempty"`

	// ClientCert requires a trusted client certificate (mTLS) on inbound
	// TLS connections, verified at the ingress handshake. The primary
	// origin-lockdown control — strongest when the CA is account-specific
	// (not a CDN's shared origin-pull CA).
	ClientCert *ExposeClientCert `json:"clientCert,omitempty" yaml:"clientCert,omitempty"`
}

ServiceExpose defines how a service is exposed externally.

type ServiceFinalizerInterface

type ServiceFinalizerInterface interface {
	DeleteService(ctx context.Context, service *Service) error
}

type ServiceMetadata

type ServiceMetadata struct {
	// Creation timestamp
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`

	// Generation of the service
	Generation int64 `json:"generation,omitempty" yaml:"generation,omitempty"`

	// TemplateGeneration tracks changes to the instance TEMPLATE — the parts
	// of the spec that define what a container looks like (image, env, mounts,
	// ports, ...) — as opposed to Generation, which advances on EVERY
	// desired-state change including scale. Cast bumps both (to the same
	// value); the scaling controller bumps only Generation. Instances record
	// TemplateGeneration at creation, and the compatibility check compares
	// against it — so a scale-up never recreates surviving containers, while
	// a spec change still does (issue #142; mirrors the K8s
	// Deployment-generation vs pod-template-hash split). Pre-existing services
	// have 0 here, which compares as "not newer than any instance" until the
	// next cast stamps it.
	TemplateGeneration int64 `json:"templateGeneration,omitempty" yaml:"templateGeneration,omitempty"`

	// ObservedGeneration is the Generation the reconciler last acted on. When it
	// equals Generation, the desired state (spec + scale) is fully reconciled, so
	// an incoming update carries only status/observed fields and reconciliation
	// can be skipped (see serviceController.isStatusOnlyChange). Every
	// desired-state change bumps Generation — including scale, which the scaling
	// controller now increments — so this single persisted field replaces the
	// in-memory serviceObservedGenerations/serviceObservedScales shadow maps and,
	// unlike them, survives a runed restart (RFC #129 Phase 2).
	ObservedGeneration int64 `json:"observedGeneration,omitempty" yaml:"observedGeneration,omitempty"`

	// OwnedBy is the system ownership stamp set when a runeset release manages
	// this service. See _docs/plugins/RUNESET_STATEFUL_RELEASES.md.
	OwnedBy *OwnedBy `json:"ownedBy,omitempty" yaml:"ownedBy,omitempty"`

	// LastNonZeroScale tracks the most recent non-zero scale to support restart semantics
	LastNonZeroScale int `json:"lastNonZeroScale,omitempty" yaml:"lastNonZeroScale,omitempty"`

	// DeletionTimestamp marks the service as being torn down (Kubernetes-style
	// foreground deletion, RFC #129 Phase 4). Once set, the reconciler drives
	// reconcileDeletion instead of reconciling toward the spec, and the record
	// is NOT removed from the store until every finalizer has cleared. Being
	// persisted, an interrupted teardown resumes on the next reconcile with no
	// separate recovery path.
	DeletionTimestamp *time.Time `json:"deletionTimestamp,omitempty" yaml:"deletionTimestamp,omitempty"`

	// Finalizers are the ordered cleanup steps that must complete before the
	// service record may be removed. Populated when DeletionTimestamp is set
	// (instance-cleanup, then volume-cleanup iff the service has claimTemplate
	// volumes). The reconciler pops each entry only after its work is fully
	// done; when the list is empty the record is deleted (the terminal
	// transition). This gate is what makes the record provably outlive its
	// instances and volumes — orphans become impossible by construction.
	Finalizers []FinalizerType `json:"finalizers,omitempty" yaml:"finalizers,omitempty"`
}

ServiceMetadata represents metadata for a service.

type ServiceNetworkPolicy

type ServiceNetworkPolicy struct {
	// Ingress rules (traffic coming into the service)
	Ingress []IngressRule `json:"ingress,omitempty" yaml:"ingress,omitempty"`

	// Egress rules (traffic going out from the service)
	Egress []EgressRule `json:"egress,omitempty" yaml:"egress,omitempty"`
}

ServiceNetworkPolicy represents a network policy embedded in a service spec.

func (*ServiceNetworkPolicy) Validate

func (s *ServiceNetworkPolicy) Validate() error

Validate checks if a service network policy is valid.

type ServicePort

type ServicePort struct {
	// Name for this port (used in references)
	Name string `json:"name" yaml:"name"`

	// Port number
	Port int `json:"port" yaml:"port"`

	// Target port (if different from port)
	TargetPort int `json:"targetPort,omitempty" yaml:"targetPort,omitempty"`

	// Protocol (default: TCP)
	Protocol string `json:"protocol,omitempty" yaml:"protocol,omitempty"`

	// HostPort, when > 0, publishes the container's port to the host on
	// 127.0.0.1:<HostPort>. Intended as a dev-mode escape hatch on
	// platforms where the cluster dataplane cannot reach the container
	// bridge IP from the host (notably macOS Docker Desktop). Production
	// services should reach services through the cluster VIP or ingress,
	// not via a published host port.
	HostPort int `json:"hostPort,omitempty" yaml:"hostPort,omitempty"`
}

ServicePort represents a port exposed by a service.

type ServiceRegistry

type ServiceRegistry struct {
	// Map of service namespaced names to endpoint information
	Services map[string]*ServiceEndpoints `json:"services" yaml:"services"`

	// Last update timestamp
	LastUpdated time.Time `json:"lastUpdated" yaml:"lastUpdated"`
}

ServiceRegistry represents the discovery registry for services.

type ServiceRegistryOverride

type ServiceRegistryOverride struct {
	Name string        `json:"name,omitempty" yaml:"name,omitempty"`
	Auth *RegistryAuth `json:"auth,omitempty" yaml:"auth,omitempty"`
}

ServiceRegistryOverride allows per-service registry selection or inline auth

func (*ServiceRegistryOverride) Validate

func (r *ServiceRegistryOverride) Validate() error

type ServiceSpec

type ServiceSpec struct {
	// Human-readable name for the service (required)
	Name string `json:"name" yaml:"name"`

	// Namespace the service belongs to (optional, defaults to "default")
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

	// Labels for the service
	Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

	// Container image for the service (required)
	Image string `json:"image" yaml:"image"`

	// Command to run in the container (overrides image CMD)
	Command string `json:"command,omitempty" yaml:"command,omitempty"`

	// Arguments to the command
	Args []string `json:"args,omitempty" yaml:"args,omitempty"`

	// Environment variables for the service
	Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`

	// Import environment variables from secrets/configmaps with optional prefix
	EnvFrom EnvFromList `json:"envFrom,omitempty" yaml:"envFrom,omitempty"`

	// Number of instances to run (default: 1)
	Scale int `json:"scale" yaml:"scale"`

	// Ports exposed by the service
	Ports []ServicePort `json:"ports,omitempty" yaml:"ports,omitempty"`

	// Resource requirements for each instance
	Resources *Resources `json:"resources,omitempty" yaml:"resources,omitempty"`

	// Health checks for the service
	Health *HealthCheck `json:"health,omitempty" yaml:"health,omitempty"`

	// Network policy for controlling traffic
	NetworkPolicy *ServiceNetworkPolicy `json:"networkPolicy,omitempty" yaml:"networkPolicy,omitempty"`

	// External exposure configuration
	Expose *ServiceExpose `json:"expose,omitempty" yaml:"expose,omitempty"`

	// Placement preferences and requirements
	Affinity *ServiceAffinity `json:"affinity,omitempty" yaml:"affinity,omitempty"`

	// Autoscaling configuration
	Autoscale *ServiceAutoscale `json:"autoscale,omitempty" yaml:"autoscale,omitempty"`

	// Secret mounts
	SecretMounts []SecretMount `json:"secretMounts,omitempty" yaml:"secretMounts,omitempty"`

	// Configmap mounts
	ConfigmapMounts []ConfigmapMount `json:"configmapMounts,omitempty" yaml:"configmapMounts,omitempty"`

	// Volume mounts. Each entry references either a pre-existing Volume by
	// name (Claim) or an inline ClaimTemplate the controller materializes
	// into a per-instance Volume.
	Volumes []VolumeMount `json:"volumes,omitempty" yaml:"volumes,omitempty"`

	// Service discovery configuration (operator-facing; no VIP field).
	Discovery *ServiceDiscoverySpec `json:"discovery,omitempty" yaml:"discovery,omitempty"`

	// Named registry selector for pulling the image (optional)
	ImageRegistry string `json:"imageRegistry,omitempty" yaml:"imageRegistry,omitempty"`

	// Registry override allowing inline auth or named selection (optional)
	Registry *ServiceRegistryOverride `json:"registry,omitempty" yaml:"registry,omitempty"`

	// ImagePull controls when the runner pulls the container image.
	// Allowed values: "always" (default), "missing", "never".
	ImagePull string `json:"imagePull,omitempty" yaml:"imagePull,omitempty"`

	// Skip indicates this spec should be ignored by castfile parsing
	Skip bool `json:"skip,omitempty" yaml:"skip,omitempty"`

	// Dependencies in user-facing form. Accepts either:
	// - FQDN strings (e.g., "db.prod.rune") as YAML sequence entries
	// - ResourceRef strings (e.g., "secret:db-creds" or "configmap:app-settings")
	// - Structured objects (service/secret/configmap with optional namespace)
	// These will be normalized to []DependencyRef in internal Service
	Dependencies []ServiceDependency `json:"dependencies,omitempty" yaml:"dependencies,omitempty"`

	// InitSteps run sequentially before each instance's main container (RUNE-121).
	InitSteps []InitStep `json:"initSteps,omitempty" yaml:"initSteps,omitempty"`

	// SecurityContext applied to the main container. Privileged and
	// seccomp=unconfined are admin-gated by the server.
	SecurityContext *SecurityContext `json:"securityContext,omitempty" yaml:"securityContext,omitempty"`
	// contains filtered or unexported fields
}

ServiceSpec is the YAML/JSON specification for a service.

func (*ServiceSpec) GetEnvWithTemplates

func (s *ServiceSpec) GetEnvWithTemplates(templateMap map[string]string) map[string]string

GetEnvWithTemplates returns environment variables with template references restored

func (*ServiceSpec) GetName

func (s *ServiceSpec) GetName() string

Implement Spec interface for ServiceSpec

func (*ServiceSpec) GetNamespace

func (s *ServiceSpec) GetNamespace() string

func (*ServiceSpec) Kind

func (s *ServiceSpec) Kind() string

func (*ServiceSpec) RestoreEnvFrom

func (s *ServiceSpec) RestoreEnvFrom(templateMap map[string]string)

RestoreEnvFrom resolves any template placeholders captured in EnvFrom.Raw using the provided templateMap, and populates Secret/Configmap/Namespace accordingly.

func (*ServiceSpec) RestoreTemplateReferences

func (s *ServiceSpec) RestoreTemplateReferences(templateMap map[string]string)

RestoreTemplateReferences restores template references in environment variables This should be called after parsing to restore the original template syntax

func (*ServiceSpec) ToService

func (s *ServiceSpec) ToService() (*Service, error)

ToService converts a ServiceSpec to a Service.

func (*ServiceSpec) Validate

func (s *ServiceSpec) Validate() error

Validate validates the service specification.

func (*ServiceSpec) ValidateStructure

func (s *ServiceSpec) ValidateStructure(data []byte) error

ValidateStructure validates the YAML structure against the service specification Deprecated: ValidateStructure is no longer used; structural checks happen in Validate via validateStructureFromNode.

type ServiceStatus

type ServiceStatus string

ServiceStatus represents the current status of a service.

const (
	// ServiceStatusPending indicates the service is being created.
	ServiceStatusPending ServiceStatus = "Pending"

	// ServiceStatusRunning indicates the service is running.
	ServiceStatusRunning ServiceStatus = "Running"

	// ServiceStatusDeploying indicates the service is being updated.
	ServiceStatusDeploying ServiceStatus = "Deploying"

	// ServiceStatusStopping indicates the service has a lower desired
	// scale than its current instance count — instances are actively being
	// torn down to reach the desired state. Set during `rune stop` and the
	// drain phase of `rune restart`. Visible distinct from "Running" so
	// operators can tell at a glance that a service is in flight, not idle.
	ServiceStatusStopping ServiceStatus = "Stopping"

	// ServiceStatusFailed indicates the service failed to deploy or run.
	ServiceStatusFailed ServiceStatus = "Failed"

	// ServiceStatusDeleted indicates the service has been deleted.
	ServiceStatusDeleted ServiceStatus = "Deleted"
)

type ServiceStatusInfo

type ServiceStatusInfo struct {
	Status ServiceStatus

	// ObservedGeneration tracks which generation was last processed by the controller
	ObservedGeneration int64 `json:"observedGeneration,omitempty" yaml:"observedGeneration,omitempty"`

	// DesiredInstances is the number of instances that should be running
	DesiredInstances int

	// RunningInstances is the number of instances that are currently running
	RunningInstances int
}

ServiceStatusInfo contains a summary of a service's status

type Snapshot

type Snapshot struct {
	NamespacedResource `json:"-" yaml:"-"`

	ID        string            `json:"id" yaml:"id"`
	Name      string            `json:"name" yaml:"name"`
	Namespace string            `json:"namespace" yaml:"namespace"`
	Labels    map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

	// SourceVolume is the bare name of the Volume in the same namespace
	// (cross-namespace snapshots are out of scope).
	SourceVolume string `json:"sourceVolume" yaml:"sourceVolume"`

	// Driver records which driver took the snapshot — needed at restore
	// time to route the call.
	Driver string `json:"driver" yaml:"driver"`

	// Handle is the driver-populated opaque snapshot identifier.
	Handle string `json:"handle,omitempty" yaml:"handle,omitempty"`

	// SizeBytes is the apparent size of the captured data.
	SizeBytes int64 `json:"sizeBytes,omitempty" yaml:"sizeBytes,omitempty"`

	// Scheduled is true if the snapshot was created by a SnapshotSchedule
	// rather than an explicit `rune snapshot create` call. Retention reaping
	// only considers scheduled snapshots.
	Scheduled bool `json:"scheduled,omitempty" yaml:"scheduled,omitempty"`

	Phase   SnapshotPhase `json:"phase" yaml:"phase"`
	Reason  string        `json:"reason,omitempty" yaml:"reason,omitempty"`
	Message string        `json:"message,omitempty" yaml:"message,omitempty"`

	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Snapshot is a namespace-scoped point-in-time copy of a Volume. Stored under snapshots/<ns>/<name> in the local store.

func (*Snapshot) Equals

func (s *Snapshot) Equals(other Resource) bool

Equals reports whether two Snapshot resources are functionally equivalent for watch purposes.

func (*Snapshot) GetID

func (s *Snapshot) GetID() string

GetID implements NamespacedResource.

func (*Snapshot) GetResourceType

func (s *Snapshot) GetResourceType() ResourceType

GetResourceType reports the resource type.

func (*Snapshot) String

func (s *Snapshot) String() string

String returns the namespaced identifier "<namespace>/<name>".

type SnapshotPhase

type SnapshotPhase string

SnapshotPhase is the lifecycle phase of a Snapshot resource.

const (
	SnapshotPhasePending  SnapshotPhase = "Pending"
	SnapshotPhaseCreating SnapshotPhase = "Creating"
	SnapshotPhaseReady    SnapshotPhase = "Ready"
	SnapshotPhaseDeleting SnapshotPhase = "Deleting"
	SnapshotPhaseFailed   SnapshotPhase = "Failed"
)

type SnapshotSchedule

type SnapshotSchedule struct {
	// Cron expression in standard 5-field format ("0 2 * * *").
	Cron string `json:"cron" yaml:"cron"`

	// Retention is the number of historical snapshots to keep. Older
	// snapshots are reaped after each successful new snapshot.
	Retention int `json:"retention,omitempty" yaml:"retention,omitempty"`
}

SnapshotSchedule configures recurring driver snapshots for a Volume.

type Spec

type Spec interface {
	// Validate ensures the spec is structurally and semantically valid.
	Validate() error
	// GetName returns the resource name declared in the spec.
	GetName() string
	// GetNamespace returns the resource namespace declared in the spec
	// (defaulting behavior may be applied by callers as needed).
	GetNamespace() string
	// Kind returns the logical resource kind (e.g., "Service", "Secret", "Config").
	Kind() string
}

Spec is a common interface implemented by all resource specs that can be validated and identify themselves by name/namespace/kind.

type StorageClass

type StorageClass struct {
	// Unique identifier for the storage class.
	ID string `json:"id" yaml:"id"`

	// DNS-1123 cluster-unique name.
	Name string `json:"name" yaml:"name"`

	// Driver is the registered driver name (e.g. "local", "local-host",
	// "do-volume", "aws-ebs"). Resolved against the storage driver registry
	// at controller boot — unknown drivers fail validation.
	Driver string `json:"driver" yaml:"driver"`

	// Parameters are driver-specific key/value settings (filesystem type,
	// IOPS, region, etc.). Volume.Parameters override these per-volume.
	Parameters map[string]string `json:"parameters,omitempty" yaml:"parameters,omitempty"`

	// ReclaimPolicy is the default reclaim policy inherited by child
	// volumes. Volume.ReclaimPolicy overrides it.
	ReclaimPolicy ReclaimPolicy `json:"reclaimPolicy,omitempty" yaml:"reclaimPolicy,omitempty"`

	// AllowedTopologies constrains both provisioning and instance placement.
	// An empty slice means no topology restriction.
	AllowedTopologies []TopologySelector `json:"allowedTopologies,omitempty" yaml:"allowedTopologies,omitempty"`

	// Default indicates this is the cluster-default class. The API server
	// enforces an at-most-one invariant — setting Default: true on a second
	// class atomically clears the previous default. claimTemplate without an
	// explicit storageClassName resolves to whichever class currently has
	// Default: true.
	Default bool `json:"default,omitempty" yaml:"default,omitempty"`

	// Labels attached to the storage class.
	Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

	// Creation timestamp.
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp.
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

StorageClass is a cluster-scoped resource describing how to provision persistent volumes via a particular storage Driver. Operators ship one StorageClass per cloud-provider+tier combination (e.g. "do-block-ssd", "aws-gp3-us-east-1"). The binary registers two built-in classes at boot: "local" (Default: true) and "local-host".

func (*StorageClass) Equals

func (s *StorageClass) Equals(other Resource) bool

Equals reports whether two StorageClass resources are functionally equivalent for watch purposes.

func (*StorageClass) GetResourceType

func (s *StorageClass) GetResourceType() ResourceType

GetResourceType reports the resource type.

func (*StorageClass) String

func (s *StorageClass) String() string

String returns the storage-class name (cluster-scoped, no namespace).

type StorageConfig

type StorageConfig struct {
	// DefaultStorageClass — see internal/config.Storage.DefaultStorageClass.
	DefaultStorageClass *string `yaml:"defaultStorageClass,omitempty"`

	// PreserveOnDelete — see internal/config.Storage.PreserveOnDelete.
	PreserveOnDelete bool `yaml:"preserveOnDelete,omitempty"`

	// AllowCreateMissing — see internal/config.Storage.AllowCreateMissing.
	AllowCreateMissing bool `yaml:"allowCreateMissing,omitempty"`

	Drivers map[string]map[string]any `yaml:"drivers,omitempty"`
}

StorageConfig mirrors internal/config.Storage. The shape of each per-driver inner map is opaque from the runefile's perspective: drivers register a factory + a parseConfig that validates whatever keys they care about. Keeping the value type as `any` lets us add new drivers without touching the runefile parser.

Example:

storage:
  defaultStorageClass: local
  preserveOnDelete: false
  allowCreateMissing: false
  drivers:
    local:
      localVolumeRoot: /var/lib/rune/volumes
    local-host:
      hostPathAllowlist:
        - /srv/data

type StoredSecret

type StoredSecret struct {
	// Name of the secret
	Name string `json:"name"`

	// Namespace of the secret
	Namespace string `json:"namespace"`

	// Version of the secret
	Version int `json:"version"`

	// Creation timestamp
	CreatedAt time.Time `json:"createdAt"`

	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt"`

	// Ciphertext of the secret
	Ciphertext []byte `json:"ciphertext"`

	// Wrapped DEK of the secret
	WrappedDEK []byte `json:"wrappedDEK"`

	// OwnedBy is the system ownership stamp. It is plaintext metadata (NOT part
	// of the encrypted payload) so a runeset release's ownership of a secret
	// survives storage and is visible to drift/adoption checks. Round-tripped by
	// encryptSecret/decryptSecret. See RUNESET_STATEFUL_RELEASES.md.
	OwnedBy *OwnedBy `json:"ownedBy,omitempty"`
}

StoredSecret is the persisted encrypted form of a Secret

type TCPRoute

type TCPRoute struct {
	// Port number for this TCP route
	Port int `json:"port" yaml:"port"`

	// Destination service and options
	Destination RouteDestination `json:"destination" yaml:"destination"`
}

TCPRoute represents a TCP routing rule.

type TLSConfig

type TLSConfig struct {
	Enabled  bool   `yaml:"enabled"`
	CertFile string `yaml:"cert_file,omitempty"`
	KeyFile  string `yaml:"key_file,omitempty"`
}

TLSConfig represents TLS configuration

type TelemetryConfig

type TelemetryConfig struct {
	MetricsAddr string `yaml:"metrics_addr,omitempty"`
}

TelemetryConfig holds the metrics endpoint configuration.

type Token

type Token struct {
	ID          string     `json:"id" yaml:"id"`
	Name        string     `json:"name" yaml:"name"`
	SubjectID   string     `json:"subjectId" yaml:"subjectId"`
	SubjectType string     `json:"subjectType" yaml:"subjectType"` // "user" | "service"
	Description string     `json:"description,omitempty" yaml:"description,omitempty"`
	IssuedAt    time.Time  `json:"issuedAt" yaml:"issuedAt"`
	ExpiresAt   *time.Time `json:"expiresAt,omitempty" yaml:"expiresAt,omitempty"`
	Revoked     bool       `json:"revoked" yaml:"revoked"`
	SecretHash  string     `json:"secretHash" yaml:"secretHash"`

	// Kind discriminates static/access/refresh (RUNE-201).
	Kind TokenKind `json:"kind,omitempty" yaml:"kind,omitempty"`

	// PrevSecretHash holds the hash of the immediately-prior refresh secret for
	// a refresh grant, set on rotation. It exists so a genuinely stale (post
	// grace-window) reuse of a rotated refresh secret can be identified and
	// treated as theft. Only meaningful when Kind==refresh.
	PrevSecretHash string `json:"prevSecretHash,omitempty" yaml:"prevSecretHash,omitempty"`

	// LastUsedAt records the last time a refresh grant was rotated (RUNE-201
	// sliding expiry). Only meaningful when Kind==refresh.
	LastUsedAt *time.Time `json:"lastUsedAt,omitempty" yaml:"lastUsedAt,omitempty"`
}

Token represents an authentication token (opaque secret stored hashed)

func (*Token) GetID

func (t *Token) GetID() string

func (*Token) GetResourceType

func (t *Token) GetResourceType() ResourceType

type TokenKind

type TokenKind string

TokenKind discriminates the role a token plays (RUNE-201). Every token is issued with an explicit kind.

const (
	// TokenKindStatic is a long-lived bearer token with no refresh: the model
	// service accounts, CI (`cast`), and the bootstrap/break-glass root token
	// use. Accepted as a request bearer.
	TokenKindStatic TokenKind = "static"

	// TokenKindAccess is a short-lived session credential minted from a
	// refresh grant. Accepted as a request bearer; expires quickly.
	TokenKindAccess TokenKind = "access"

	// TokenKindRefresh is a long-lived grant secret. It is NEVER a valid
	// request bearer — it is accepted only by the refresh endpoint. This is
	// the load-bearing rule of RUNE-201: if a refresh token were accepted as
	// a bearer, the short-lived-access design collapses.
	TokenKindRefresh TokenKind = "refresh"
)

type TopologyMatchExpression

type TopologyMatchExpression struct {
	// Key is the label name (e.g. "rune.io/zone").
	Key string `json:"key" yaml:"key"`

	// Operator is one of: In, NotIn, Exists, DoesNotExist.
	Operator TopologyOperator `json:"operator" yaml:"operator"`

	// Values is the set of allowed/disallowed values. Required for In/NotIn,
	// must be empty for Exists/DoesNotExist.
	Values []string `json:"values,omitempty" yaml:"values,omitempty"`
}

TopologyMatchExpression is a set-based label requirement.

type TopologyOperator

type TopologyOperator string

TopologyOperator names the set-based operators supported by TopologyMatchExpression.

const (
	TopologyOperatorIn           TopologyOperator = "In"
	TopologyOperatorNotIn        TopologyOperator = "NotIn"
	TopologyOperatorExists       TopologyOperator = "Exists"
	TopologyOperatorDoesNotExist TopologyOperator = "DoesNotExist"
)

type TopologySelector

type TopologySelector struct {
	// MatchLabels is a map of {key: value} pairs. All pairs must match.
	MatchLabels map[string]string `json:"matchLabels,omitempty" yaml:"matchLabels,omitempty"`

	// MatchExpressions allows expressing set-based requirements (e.g.
	// "key rune.io/zone In [us-east-1a, us-east-1b]"). Use this when a
	// single class needs to span multiple zones — duplicate keys in
	// MatchLabels would silently collapse to the last value.
	MatchExpressions []TopologyMatchExpression `json:"matchExpressions,omitempty" yaml:"matchExpressions,omitempty"`
}

TopologySelector matches nodes (and provisioning topologies) by label. MatchLabels and MatchExpressions are AND-ed together.

func (TopologySelector) Matches

func (s TopologySelector) Matches(labels map[string]string) bool

Matches reports whether the given label set satisfies the selector. MatchLabels and MatchExpressions are AND-ed: every key in MatchLabels must be present with the listed value, and every expression must evaluate true. An empty selector (no MatchLabels and no MatchExpressions) matches any label set.

Operator semantics:

  • In: label is present and its value is one of Values.
  • NotIn: label is absent OR its value is not one of Values.
  • Exists: label key is present (Values ignored).
  • DoesNotExist: label key is absent (Values ignored).

An expression with an unknown Operator is treated as non-matching; callers that need stricter validation should validate selectors at admission time.

type UIConfig

type UIConfig struct {
	// Enabled turns the dashboard (and the HTTP serving layer) on/off.
	Enabled bool `yaml:"enabled,omitempty"`
	// Path is the dashboard mount point (default /ui).
	Path string `yaml:"path,omitempty"`
	// HandoffEnabled allows the `rune ui` token-handoff flow.
	HandoffEnabled bool `yaml:"handoff_enabled,omitempty"`
	// HandoffTTL bounds a one-time handoff code's lifetime.
	HandoffTTL time.Duration `yaml:"handoff_ttl,omitempty"`
	// RequireTLS refuses to serve the UI over plaintext on a non-loopback
	// address (binds 127.0.0.1 only when TLS is off).
	RequireTLS bool `yaml:"require_tls,omitempty"`
}

UIConfig is the runefile-side view of the embedded dashboard settings (RUNE-200). Parallel to internal/config.UI.

type User

type User struct {
	ID        string    `json:"id" yaml:"id"`
	Name      string    `json:"name" yaml:"name"`
	Email     string    `json:"email,omitempty" yaml:"email,omitempty"`
	Policies  []string  `json:"policies,omitempty" yaml:"policies,omitempty"`
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
}

User represents an identity

func (*User) GetID

func (u *User) GetID() string

func (*User) GetResourceType

func (u *User) GetResourceType() ResourceType

type ValidationError

type ValidationError struct {
	Message string
}

ValidationError represents an error that occurs during validation.

func NewValidationError

func NewValidationError(message string) *ValidationError

NewValidationError creates a new ValidationError with the given message.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error returns the error message.

type Volume

type Volume struct {
	NamespacedResource `json:"-" yaml:"-"`

	// Unique identifier for the volume.
	ID string `json:"id" yaml:"id"`

	// DNS-1123 unique name within the namespace.
	Name string `json:"name" yaml:"name"`

	// Namespace the volume belongs to.
	Namespace string `json:"namespace" yaml:"namespace"`

	// Labels attached to the volume for organization.
	Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

	// OwnedBy is the system ownership stamp set when a runeset release manages
	// this volume. See _docs/plugins/RUNESET_STATEFUL_RELEASES.md.
	OwnedBy *OwnedBy `json:"ownedBy,omitempty" yaml:"ownedBy,omitempty"`

	// StorageClassName references the StorageClass used to provision this
	// volume. The class's driver, parameters, reclaimPolicy and
	// allowedTopologies are inherited unless overridden on the Volume.
	StorageClassName string `json:"storageClassName" yaml:"storageClassName"`

	// Size as a human-readable string (e.g. "10Gi"). Validation lives in the
	// API server / cast linter.
	Size string `json:"size" yaml:"size"`

	// AccessMode requested by the workload. Must be in the driver's
	// Capabilities.AccessModes.
	AccessMode AccessMode `json:"accessMode" yaml:"accessMode"`

	// ReclaimPolicy overrides the inherited StorageClass policy for this
	// volume only. Empty defers to the StorageClass.
	ReclaimPolicy ReclaimPolicy `json:"reclaimPolicy,omitempty" yaml:"reclaimPolicy,omitempty"`

	// Parameters are driver-specific overrides merged on top of
	// StorageClass.Parameters. Example: hostPath for the local-host driver.
	Parameters map[string]string `json:"parameters,omitempty" yaml:"parameters,omitempty"`

	// DriverParameters is a controller-owned snapshot of
	// `mergeParameters(StorageClass.Parameters, Volume.Parameters)`
	// captured at successful Provision time. The reclaim path
	// (Delete) and the node agent (Detach, Unmount) consult it when
	// the live StorageClass has been deleted before its volumes —
	// drivers like do-volume need region / auth references for those
	// calls and would otherwise have nothing to work from.
	//
	// Always controller-managed; users SHOULD NOT set this in cast
	// files. Excluded from secret-bearing fields per design — secret
	// references survive here but their resolved values do not. See
	// RUNE-200 PR 2.
	DriverParameters map[string]string `json:"driverParameters,omitempty" yaml:"driverParameters,omitempty"`

	// SnapshotSchedule, when set, instructs the controller to create
	// scheduled snapshots via the worker pool.
	SnapshotSchedule *SnapshotSchedule `json:"snapshotSchedule,omitempty" yaml:"snapshotSchedule,omitempty"`

	// Handle is the driver-populated opaque identifier returned by Provision.
	// The controller treats it as a string; the owning driver re-parses it.
	Handle string `json:"handle,omitempty" yaml:"handle,omitempty"`

	// UsedBytes / CapacityBytes are live usage figures attached by the API
	// read path from drivers that implement the UsageReporter capability.
	// TRANSIENT: excluded from store serialization (json/yaml "-") so stale
	// samples are never persisted. 0 means unknown.
	UsedBytes     uint64 `json:"-" yaml:"-"`
	CapacityBytes uint64 `json:"-" yaml:"-"`

	// OwnerService is set on volumes auto-created from a claimTemplate so the
	// controller knows whose deletion may trigger reclaim.
	// Format: "<namespace>/<service-name>".
	OwnerService string `json:"ownerService,omitempty" yaml:"ownerService,omitempty"`

	// BoundNode is the node where the volume is currently attached, if any.
	BoundNode string `json:"boundNode,omitempty" yaml:"boundNode,omitempty"`

	// BoundClaim records what the volume is bound to. Format:
	// "<service>/<mountName>[/<ordinal>]".
	BoundClaim string `json:"boundClaim,omitempty" yaml:"boundClaim,omitempty"`

	// Status is the lifecycle phase. Controller-managed.
	Status VolumeStatus `json:"status" yaml:"status"`

	// StatusReason is a short machine-readable code explaining the status
	// (e.g. "HostPathMissing", "ProvisionTimeout"). Named to match
	// Service/Instance/Node StatusReason so `rune describe` reads one
	// field across every resource type.
	StatusReason string `json:"statusReason,omitempty" yaml:"statusReason,omitempty"`

	// Message is a human-readable description of the status.
	Message string `json:"message,omitempty" yaml:"message,omitempty"`

	// InitializedFor records the wall-clock timestamp at which an init
	// step (RUNE-121) belonging to a given service ran to Succeeded
	// against this volume. Keys are service IDs ("<namespace>/<name>"
	// for namespaced services). Used as the freshness anchor for
	// runIf=freshVolume so that subsequent restarts and crash-recovery
	// skip the step on volumes that already carry initialised data.
	// Cleared by the volume controller on reclaim.
	InitializedFor map[string]time.Time `json:"initializedFor,omitempty" yaml:"initializedFor,omitempty"`

	// Creation timestamp.
	CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`

	// Last update timestamp.
	UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
}

Volume is a namespace-scoped persistent storage resource managed by a Driver. Stored under volumes/<ns>/<name> in the local store.

func (*Volume) Equals

func (v *Volume) Equals(other Resource) bool

Equals reports whether two Volume resources are functionally equivalent for watch purposes.

func (*Volume) GetID

func (v *Volume) GetID() string

GetID implements NamespacedResource.

func (*Volume) GetResourceType

func (v *Volume) GetResourceType() ResourceType

GetResourceType implements NamespacedResource.

func (*Volume) String

func (v *Volume) String() string

String returns the namespaced identifier "<namespace>/<name>".

type VolumeClaim

type VolumeClaim struct {
	// Name is the bare name (resolved in the service's namespace) or
	// "<namespace>/<name>" for cross-namespace claims.
	Name string `json:"name" yaml:"name"`
}

VolumeClaim is a reference to an existing Volume.

type VolumeClaimTemplate

type VolumeClaimTemplate struct {
	StorageClassName string            `json:"storageClassName,omitempty" yaml:"storageClassName,omitempty"`
	Size             string            `json:"size" yaml:"size"`
	AccessMode       AccessMode        `json:"accessMode" yaml:"accessMode"`
	Parameters       map[string]string `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	ReclaimPolicy    ReclaimPolicy     `json:"reclaimPolicy,omitempty" yaml:"reclaimPolicy,omitempty"`
}

VolumeClaimTemplate causes the controller to auto-provision one Volume per replica of the owning service. The generated volume name is "<mount>-<service>-<ordinal>" with OwnerService set on each.

type VolumeMount

type VolumeMount struct {
	// Name is a service-local identifier for the mount.
	Name string `json:"name" yaml:"name"`

	// MountPath is the absolute container path the volume is mounted at.
	MountPath string `json:"mountPath" yaml:"mountPath"`

	// ReadOnly mounts the volume read-only inside the container.
	ReadOnly bool `json:"readOnly,omitempty" yaml:"readOnly,omitempty"`

	// SubPath optionally selects a sub-path within the volume to mount
	// (parity with k8s subPath; useful for sharing one volume across mounts).
	SubPath string `json:"subPath,omitempty" yaml:"subPath,omitempty"`

	// Claim references an existing Volume by name (bare name resolves to the
	// service's namespace; "<ns>/<name>" supports cross-namespace claims).
	Claim *VolumeClaim `json:"claim,omitempty" yaml:"claim,omitempty"`

	// ClaimTemplate provisions per-replica volumes, k8s-StatefulSet style.
	ClaimTemplate *VolumeClaimTemplate `json:"claimTemplate,omitempty" yaml:"claimTemplate,omitempty"`

	// FSUser, if set, owns the mount root after the volume is attached.
	// Pointer so absent/0 are distinguishable. Solves the "fresh ext4
	// is owned by root, container runs as uid 1000, EACCES on first
	// write" pattern without an init step. Applied idempotently once
	// per reconcile — the chown is skipped when the current uid
	// already matches.
	FSUser *int `json:"fsUser,omitempty" yaml:"fsUser,omitempty"`

	// FSGroup, if set, owns the mount root after the volume is
	// attached. Same idempotent semantics as FSUser.
	FSGroup *int `json:"fsGroup,omitempty" yaml:"fsGroup,omitempty"`

	// FSMode, if set, is chmod'd onto the mount root. Octal string
	// ("0775", "0750") so leading zero survives YAML parsing.
	// Idempotent — applied only when current mode differs.
	FSMode string `json:"fsMode,omitempty" yaml:"fsMode,omitempty"`
}

VolumeMount declares a volume reference inside a Service or Job container. Exactly one of Claim or ClaimTemplate must be set; the other is nil.

type VolumeStatus

type VolumeStatus string

VolumeStatus is the lifecycle phase of a Volume resource.

const (
	VolumeStatusPending      VolumeStatus = "Pending"
	VolumeStatusProvisioning VolumeStatus = "Provisioning"
	VolumeStatusAvailable    VolumeStatus = "Available"
	VolumeStatusBound        VolumeStatus = "Bound"
	VolumeStatusReleased     VolumeStatus = "Released"
	VolumeStatusStalled      VolumeStatus = "Stalled"
	VolumeStatusFailed       VolumeStatus = "Failed"
)

Jump to

Keyboard shortcuts

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