db

package
v1.0.38 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const GlobalSettingsID = "global-settings"

Global Settings operations (using ServerConfig with a special ID)

Variables

View Source
var ErrScheduledTaskNotFound = errors.New("scheduled task not found")

ErrScheduledTaskNotFound is returned when a scheduled task ID does not exist. It lets the RPC layer map a missing task to connect.CodeNotFound instead of an internal error.

View Source
var ErrServerConfigNotFound = errors.New("server config not found")

ErrServerConfigNotFound indicates that a server has no persisted config row.

Functions

func DiffMaps

func DiffMaps(current, desired map[string]any) map[string]any

DiffMaps returns the subset of desired whose values differ from current. Keys are ServerConfig JSON field names. A key missing from current counts as different; explicit nil is a meaningful value (clear the field).

func MergeMaps

func MergeMaps(base, overlay map[string]any) map[string]any

MergeMaps returns base with every entry of overlay applied on top.

func NextRunAfter

func NextRunAfter(expr string, ref time.Time) (time.Time, error)

NextRunAfter returns the first scheduled fire time strictly after ref.

func NormalizeModLoaderForType

func NormalizeModLoaderForType(loader ModLoader) string

NormalizeModLoaderForType normalizes modloader string to uppercase TYPE for Minecraft server containers

func PanelBackupFilename

func PanelBackupFilename(now time.Time) string

PanelBackupFilename is the snapshot name for a calendar day.

func PrunePanelBackups

func PrunePanelBackups(dir string, keep int) error

PrunePanelBackups deletes daily snapshots beyond keep, oldest first.

func ServerConfigToMap

func ServerConfigToMap(cfg *ServerConfig) (map[string]any, error)

ServerConfigToMap renders a ServerConfig as a JSON-field-name map so staged payloads can be diffed and merged generically.

func ValidateCronExpr

func ValidateCronExpr(expr string) error

ValidateCronExpr reports whether expr is a parseable 5-field cron expression.

Types

type APIToken

type APIToken struct {
	ID            string     `json:"id" gorm:"primaryKey"`
	UserID        string     `json:"user_id" gorm:"not null;index;column:user_id"`
	Name          string     `json:"name" gorm:"not null"`
	TokenHash     string     `json:"-" gorm:"not null;uniqueIndex;column:token_hash"`
	ExpiresAt     *time.Time `json:"expires_at" gorm:"column:expires_at"`
	LastUsedAt    *time.Time `json:"last_used_at" gorm:"column:last_used_at"`
	IsModuleToken bool       `json:"is_module_token" gorm:"default:false;column:is_module_token"`
	CreatedAt     time.Time  `json:"created_at" gorm:"autoCreateTime"`
	User          *User      `json:"-" gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`
}

APIToken represents a long-lived API token for programmatic access

type ActivityLog

type ActivityLog struct {
	ID         string `json:"id" gorm:"primaryKey"`
	ActorID    string `json:"actor_id" gorm:"index;column:actor_id"`
	ActorName  string `json:"actor_name" gorm:"column:actor_name"`
	IP         string `json:"ip"`
	Event      string `json:"event" gorm:"not null;index"`
	SubjectTyp string `json:"subject_type" gorm:"index;column:subject_type"` // e.g. "server", "user"
	SubjectID  string `json:"subject_id" gorm:"index;column:subject_id"`
	Properties string `json:"properties" gorm:"type:text"` // JSON details

	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;index"`
}

ActivityLog is an append-only audit trail (MINE-141) for mutating ops: auth, power, file, backup, subuser and schedule actions.

type BackupRecord

type BackupRecord struct {
	ID        string `json:"id" gorm:"primaryKey"`
	ServerID  string `json:"server_id" gorm:"not null;index;column:server_id"`
	Name      string `json:"name" gorm:"not null"`
	Path      string `json:"path" gorm:"not null"`
	SizeBytes int64  `json:"size_bytes" gorm:"column:size_bytes"`
	SHA256    string `json:"sha256"`
	Locked    bool   `json:"locked" gorm:"default:false"`
	Status    string `json:"status" gorm:"default:complete"`      // complete, restoring, failed
	RemoteKey string `json:"remote_key" gorm:"column:remote_key"` // S3 object key when offloaded (MINE-138)

	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;index"`
}

BackupRecord tracks an on-disk backup archive (MINE-138). The archive itself lives under the backup dir; this row carries integrity + lock state.

type ExecutionStatus

type ExecutionStatus string

ExecutionStatus defines the status of a task execution

const (
	ExecutionStatusPending   ExecutionStatus = "pending"   // Queued for execution
	ExecutionStatusRunning   ExecutionStatus = "running"   // Currently executing
	ExecutionStatusCompleted ExecutionStatus = "completed" // Finished successfully
	ExecutionStatusFailed    ExecutionStatus = "failed"    // Failed with error
	ExecutionStatusSkipped   ExecutionStatus = "skipped"   // Skipped (e.g., server offline)
	ExecutionStatusCancelled ExecutionStatus = "cancelled" // Cancelled by user
	ExecutionStatusTimeout   ExecutionStatus = "timeout"   // Timed out
)

type IndexedModpack

type IndexedModpack struct {
	ID            string    `json:"id" gorm:"primaryKey"`                      // Format: "indexer-originalId"
	IndexerID     string    `json:"indexer_id" gorm:"index;column:indexer_id"` // Original ID from indexer
	Indexer       string    `json:"indexer" gorm:"index"`                      // "fuego", "modrinth", etc.
	Name          string    `json:"name" gorm:"not null;index"`
	Slug          string    `json:"slug" gorm:"index"`
	Summary       string    `json:"summary"`
	Description   string    `json:"description" gorm:"type:text"`
	LogoURL       string    `json:"logo_url" gorm:"column:logo_url"`
	WebsiteURL    string    `json:"website_url" gorm:"column:website_url"`
	DownloadCount int64     `json:"download_count" gorm:"column:download_count"`
	Categories    string    `json:"categories"`    // JSON array stored as string
	GameVersions  string    `json:"game_versions"` // JSON array stored as string
	ModLoaders    string    `json:"mod_loaders"`   // JSON array stored as string
	LatestFileID  string    `json:"latest_file_id" gorm:"column:latest_file_id"`
	DateCreated   time.Time `json:"date_created" gorm:"column:date_created"`
	DateModified  time.Time `json:"date_modified" gorm:"column:date_modified"`
	DateReleased  time.Time `json:"date_released" gorm:"column:date_released"`
	UpdatedAt     time.Time `json:"updated_at" gorm:"autoUpdateTime"`
	IndexedAt     time.Time `json:"indexed_at" gorm:"autoCreateTime"`
	// Computed fields for server creation
	MCVersion      string `json:"mc_version" gorm:"column:mc_version"`           // Primary MC version
	JavaVersion    string `json:"java_version" gorm:"column:java_version"`       // Required Java version
	DockerImage    string `json:"docker_image" gorm:"column:docker_image"`       // Recommended Docker image
	RecommendedRAM int    `json:"recommended_ram" gorm:"column:recommended_ram"` // Recommended RAM in MB
	IndexError     string `json:"index_error" gorm:"column:index_error"`         // Last indexer/sync error (MOD-2)
}

type IndexedModpackFile

type IndexedModpackFile struct {
	ID               string          `json:"id" gorm:"primaryKey"`
	ModpackID        string          `json:"modpack_id" gorm:"index;column:modpack_id"`
	DisplayName      string          `json:"display_name" gorm:"column:display_name"`
	FileName         string          `json:"file_name" gorm:"column:file_name"`
	FileDate         time.Time       `json:"file_date" gorm:"column:file_date"`
	FileLength       int64           `json:"file_length" gorm:"column:file_length"`
	ReleaseType      string          `json:"release_type" gorm:"column:release_type"` // "release", "beta", "alpha"
	DownloadURL      string          `json:"download_url" gorm:"column:download_url"`
	GameVersions     string          `json:"game_versions"` // JSON array stored as string
	ModLoader        string          `json:"mod_loader" gorm:"column:mod_loader"`
	ServerPackFileID *string         `json:"server_pack_file_id" gorm:"column:server_pack_file_id"`
	Sha256           string          `json:"sha256" gorm:"column:sha256"` // SHA256 checksum (MOD-4)
	Modpack          *IndexedModpack `json:"-" gorm:"foreignKey:ModpackID;constraint:OnDelete:CASCADE"`
}

type Mod

type Mod struct {
	ID          string    `json:"id" gorm:"primaryKey"`
	ServerID    string    `json:"server_id" gorm:"not null;index;column:server_id"`
	Name        string    `json:"name" gorm:"not null"`
	FileName    string    `json:"file_name" gorm:"not null;column:file_name"`
	Version     string    `json:"version"`
	ModID       string    `json:"mod_id" gorm:"column:mod_id"`
	Description string    `json:"description"`
	Enabled     bool      `json:"enabled" gorm:"default:true"`
	UploadedAt  time.Time `json:"uploaded_at" gorm:"autoCreateTime;column:uploaded_at"`
	FileSize    int64     `json:"file_size" gorm:"column:file_size"`
	Server      *Server   `json:"-" gorm:"foreignKey:ServerID;constraint:OnDelete:CASCADE"`
}

type ModLoader

type ModLoader string
const (
	// Vanilla
	ModLoaderVanilla ModLoader = "vanilla"

	// Forge-based
	ModLoaderForge    ModLoader = "forge"
	ModLoaderNeoForge ModLoader = "neoforge"

	// Fabric-based
	ModLoaderFabric ModLoader = "fabric"
	ModLoaderQuilt  ModLoader = "quilt"

	// Bukkit-based
	ModLoaderBukkit ModLoader = "bukkit"
	ModLoaderSpigot ModLoader = "spigot"

	// Paper-based
	ModLoaderPaper      ModLoader = "paper"
	ModLoaderPurpur     ModLoader = "purpur"
	ModLoaderPufferfish ModLoader = "pufferfish"
	ModLoaderFolia      ModLoader = "folia"

	// Hybrids (Forge + Bukkit)
	ModLoaderMagma           ModLoader = "magma"
	ModLoaderMagmaMaintained ModLoader = "magma_maintained"
	ModLoaderKetting         ModLoader = "ketting"
	ModLoaderMohist          ModLoader = "mohist"
	ModLoaderYouer           ModLoader = "youer"
	ModLoaderBanner          ModLoader = "banner"
	ModLoaderCatserver       ModLoader = "catserver"
	ModLoaderArclight        ModLoader = "arclight"

	// Sponge
	ModLoaderSpongeVanilla ModLoader = "spongevanilla"

	// Others
	ModLoaderLimbo     ModLoader = "limbo"
	ModLoaderNanoLimbo ModLoader = "nanolimbo"
	ModLoaderCrucible  ModLoader = "crucible"
	ModLoaderGlowstone ModLoader = "glowstone"
	ModLoaderCustom    ModLoader = "custom"

	// Modpack Platforms
	ModLoaderAutoCurseForge ModLoader = "auto_curseforge"
	ModLoaderCurseForge     ModLoader = "curseforge"
	ModLoaderFTBA           ModLoader = "ftba"
	ModLoaderModrinth       ModLoader = "modrinth"
)

type ModpackFavorite

type ModpackFavorite struct {
	ID        string          `json:"id" gorm:"primaryKey"`
	ModpackID string          `json:"modpack_id" gorm:"index;column:modpack_id"`
	CreatedAt time.Time       `json:"created_at" gorm:"autoCreateTime"`
	Modpack   *IndexedModpack `json:"modpack,omitempty" gorm:"foreignKey:ModpackID;constraint:OnDelete:CASCADE"`
}

type Module

type Module struct {
	ID          string       `json:"id" gorm:"primaryKey"`
	Name        string       `json:"name" gorm:"not null"`
	ServerID    string       `json:"server_id" gorm:"not null;index;column:server_id"`
	TemplateID  string       `json:"template_id" gorm:"not null;index;column:template_id"`
	NodeID      string       `json:"node_id" gorm:"column:node_id;default:'default'"`
	ContainerID string       `json:"container_id" gorm:"column:container_id"`
	Status      ModuleStatus `json:"status" gorm:"not null;default:stopped"`

	// Instance configuration (JSON - merged with template defaults)
	Config          string `json:"config" gorm:"type:text"`
	EnvOverrides    string `json:"env_overrides" gorm:"type:text;column:env_overrides"`
	VolumeOverrides string `json:"volume_overrides" gorm:"type:text;column:volume_overrides"`

	// Resource limits
	Memory   int     `json:"memory" gorm:"default:512"`
	CPULimit float64 `json:"cpu_limit" gorm:"column:cpu_limit"`

	// Container user (supports alias substitution, e.g. "{{host.uid}}")
	UID string `json:"uid" gorm:"column:uid;default:''"`
	GID string `json:"gid" gorm:"column:gid;default:''"`

	// Lifecycle
	AutoStart             bool   `json:"auto_start" gorm:"default:false;column:auto_start"`
	FollowServerLifecycle bool   `json:"follow_server_lifecycle" gorm:"default:true;column:follow_server_lifecycle"`
	Detached              bool   `json:"detached" gorm:"default:false"`
	DataPath              string `json:"data_path" gorm:"column:data_path"`

	// Timestamps
	CreatedAt   time.Time  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt   time.Time  `json:"updated_at" gorm:"autoUpdateTime"`
	LastStarted *time.Time `json:"last_started" gorm:"column:last_started"`

	// Port configuration: host:container, tcp/udp, proxy
	Ports []*v1.ModulePort `json:"ports" gorm:"column:ports;serializer:json"`

	// Module dependencies (started before this module)
	Dependencies []*v1.ModuleDependency `json:"dependencies" gorm:"column:dependencies;serializer:json"`

	// Health check configuration for dependency waiting
	HealthCheckInterval int `json:"health_check_interval" gorm:"column:health_check_interval;default:30"`
	HealthCheckTimeout  int `json:"health_check_timeout" gorm:"column:health_check_timeout;default:5"`
	HealthCheckRetries  int `json:"health_check_retries" gorm:"column:health_check_retries;default:3"`

	// Event hooks for server lifecycle integration
	EventHooks []*v1.ModuleEventHook `json:"event_hooks" gorm:"column:event_hooks;serializer:json"`

	// Instance metadata (merged with/overrides template metadata)
	Metadata map[string]string `json:"metadata" gorm:"column:metadata;serializer:json"`

	// Optional command override (overrides template's default_cmd)
	CmdOverride string `json:"cmd_override" gorm:"column:cmd_override"`

	// Init command to exec inside the container after start
	InitCommand      string `json:"init_command" gorm:"column:init_command;default:''"`
	InitCommandDelay int    `json:"init_command_delay" gorm:"column:init_command_delay;default:0"`
	RestartAfterInit bool   `json:"restart_after_init" gorm:"column:restart_after_init;default:false"`

	// Access URL templates
	AccessUrls []string `json:"access_urls" gorm:"column:access_urls;serializer:json"`

	// Creator tracking and module API token
	CreatedBy      string `json:"created_by" gorm:"column:created_by"`
	TokenID        string `json:"token_id" gorm:"column:token_id"`
	TokenPlaintext string `json:"-" gorm:"column:token_plaintext"`

	// Relationships
	Server   *Server         `json:"-" gorm:"foreignKey:ServerID;constraint:OnDelete:CASCADE"`
	Template *ModuleTemplate `json:"-" gorm:"foreignKey:TemplateID;constraint:OnDelete:RESTRICT"`

	// Runtime stats (not persisted)
	MemoryUsage float64 `json:"memory_usage" gorm:"-"`
	CPUPercent  float64 `json:"cpu_percent" gorm:"-"`
}

Module represents a running instance of a module template attached to a server

type ModuleStatus

type ModuleStatus string

ModuleStatus defines the runtime state of a module

const (
	ModuleStatusStopped  ModuleStatus = "stopped"
	ModuleStatusStarting ModuleStatus = "starting"
	ModuleStatusRunning  ModuleStatus = "running"
	ModuleStatusStopping ModuleStatus = "stopping"
	ModuleStatusError    ModuleStatus = "error"
	ModuleStatusCreating ModuleStatus = "creating"
)

type ModuleTemplate

type ModuleTemplate struct {
	ID              string             `json:"id" gorm:"primaryKey"`
	Name            string             `json:"name" gorm:"not null;uniqueIndex"`
	Description     string             `json:"description"`
	Type            ModuleTemplateType `json:"type" gorm:"not null;default:custom"`
	DockerImage     string             `json:"docker_image" gorm:"not null;column:docker_image"`
	DefaultEnv      string             `json:"default_env" gorm:"type:text;column:default_env"` // JSON map of default env vars
	DefaultVolumes  string             `json:"default_volumes" gorm:"type:text;column:default_volumes"`
	HealthCheckPath string             `json:"health_check_path" gorm:"column:health_check_path"`
	HealthCheckPort int                `json:"health_check_port" gorm:"column:health_check_port"`
	RequiresServer  bool               `json:"requires_server" gorm:"default:true;column:requires_server"`
	SupportsProxy   bool               `json:"supports_proxy" gorm:"default:true;column:supports_proxy"`
	Icon            string             `json:"icon"`
	Category        string             `json:"category"`
	Documentation   string             `json:"documentation"`
	CreatedAt       time.Time          `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt       time.Time          `json:"updated_at" gorm:"autoUpdateTime"`

	// Port configuration: host:container, tcp/udp, proxy
	Ports []*v1.ModulePort `json:"ports" gorm:"column:ports;serializer:json"`

	// Suggested module dependencies
	SuggestedDependencies []string `json:"suggested_dependencies" gorm:"column:suggested_dependencies;serializer:json"`

	// Default event hooks for server lifecycle integration
	DefaultHooks []*v1.ModuleEventHook `json:"default_hooks" gorm:"column:default_hooks;serializer:json"`

	// Display metadata (key:value pairs for notes, instructions, links, etc.)
	Metadata map[string]string `json:"metadata" gorm:"column:metadata;serializer:json"`

	// Optional command to run in the container (overrides image CMD, not ENTRYPOINT)
	DefaultCmd string `json:"default_cmd" gorm:"column:default_cmd"`

	// Default access URL templates
	DefaultAccessUrls []string `json:"default_access_urls" gorm:"column:default_access_urls;serializer:json"`

	// Default resource limits
	DefaultMemory int `json:"default_memory" gorm:"column:default_memory;default:512"` // Default memory in MB

	// Default UID/GID for container user
	DefaultUID string `json:"default_uid" gorm:"column:default_uid;default:''"`
	DefaultGID string `json:"default_gid" gorm:"column:default_gid;default:''"`

	// Init command to exec inside the container after start
	DefaultInitCommand      string `json:"default_init_command" gorm:"column:default_init_command;default:''"`
	DefaultInitCommandDelay int    `json:"default_init_command_delay" gorm:"column:default_init_command_delay;default:0"`
	DefaultRestartAfterInit bool   `json:"default_restart_after_init" gorm:"column:default_restart_after_init;default:false"`
}

ModuleTemplate represents a blueprint for creating modules

type ModuleTemplateType

type ModuleTemplateType string

ModuleTemplateType defines whether a module template is built-in or custom

const (
	ModuleTemplateTypeBuiltin ModuleTemplateType = "builtin"
	ModuleTemplateTypeCustom  ModuleTemplateType = "custom"
)

type Node

type Node struct {
	ID            string     `json:"id" gorm:"primaryKey"`
	Name          string     `json:"name" gorm:"not null;uniqueIndex"`
	Host          string     `json:"host" gorm:"not null"` // e.g. "unix:///var/run/docker.sock", "tcp://192.168.1.50:2376", "ssh://user@host"
	AdvertisedIP  string     `json:"advertised_ip" gorm:"column:advertised_ip"`
	TLSCACert     string     `json:"tls_ca_cert,omitempty" gorm:"column:tls_ca_cert;type:text"`
	TLSCert       string     `json:"tls_cert,omitempty" gorm:"column:tls_cert;type:text"`
	TLSKey        string     `json:"tls_key,omitempty" gorm:"column:tls_key;type:text"`
	TLSEnabled    bool       `json:"tls_enabled" gorm:"column:tls_enabled;default:false"`
	TLSSkipVerify bool       `json:"tls_skip_verify" gorm:"column:tls_skip_verify;default:false"`
	MaxMemoryMB   int64      `json:"max_memory_mb" gorm:"column:max_memory_mb;default:0"` // 0 = unlimited
	MaxServers    int        `json:"max_servers" gorm:"column:max_servers;default:0"`     // 0 = unlimited
	Enabled       bool       `json:"enabled" gorm:"not null;default:true"`
	Status        NodeStatus `json:"status" gorm:"not null;default:'offline'"`
	IsLocal       bool       `json:"is_local" gorm:"column:is_local;default:false"`
	LastHeartbeat *time.Time `json:"last_heartbeat" gorm:"column:last_heartbeat"`
	CreatedAt     time.Time  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt     time.Time  `json:"updated_at" gorm:"autoUpdateTime"`

	// Runtime stats (not persisted to DB)
	AllocatedMemoryMB int64 `json:"allocated_memory_mb" gorm:"-"`
	ServerCount       int   `json:"server_count" gorm:"-"`
	RunningCount      int   `json:"running_count" gorm:"-"`
	TotalMemoryMB     int64 `json:"total_memory_mb" gorm:"-"`
	AvailableMemoryMB int64 `json:"available_memory_mb" gorm:"-"`
}

Node represents a remote or local Docker daemon host

type NodeStatus

type NodeStatus string

NodeStatus defines the health and connectivity status of a Docker node

const (
	NodeStatusOnline  NodeStatus = "online"
	NodeStatusOffline NodeStatus = "offline"
	NodeStatusError   NodeStatus = "error"
)

type PortConflict

type PortConflict struct {
	Module   *Module
	Port     int
	Protocol string
	Reason   string
}

PortConflict represents a port conflict with details

type ProxyConfig

type ProxyConfig struct {
	ID        string    `json:"id" gorm:"primaryKey"`
	Enabled   bool      `json:"enabled" gorm:"not null;default:false"`
	BaseURL   string    `json:"base_url" gorm:"column:base_url"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}

ProxyConfig stores the global proxy configuration

type ProxyListener

type ProxyListener struct {
	ID            string    `json:"id" gorm:"primaryKey"`
	Port          int       `json:"port" gorm:"not null;uniqueIndex"`
	Name          string    `json:"name"` // e.g., "Primary", "Secondary", "Development"
	Description   string    `json:"description"`
	Enabled       bool      `json:"enabled" gorm:"not null;default:true"`
	IsDefault     bool      `json:"is_default" gorm:"not null;default:false"`
	ProxyProtocol bool      `json:"proxy_protocol" gorm:"not null;default:false"`
	CreatedAt     time.Time `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt     time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}

ProxyListener represents an individual proxy listening port configuration

type RegistrationInvite

type RegistrationInvite struct {
	ID          string     `json:"id" gorm:"primaryKey"`
	Code        string     `json:"code" gorm:"not null;uniqueIndex"`
	Description string     `json:"description"`
	Roles       []string   `json:"roles" gorm:"column:roles;serializer:json"`
	PinHash     string     `json:"-" gorm:"column:pin_hash"`
	MaxUses     int        `json:"max_uses" gorm:"default:0;column:max_uses"`
	UseCount    int        `json:"use_count" gorm:"default:0;column:use_count"`
	ExpiresAt   *time.Time `json:"expires_at" gorm:"column:expires_at"`
	CreatedBy   string     `json:"created_by" gorm:"not null;column:created_by"`
	CreatedAt   time.Time  `json:"created_at" gorm:"autoCreateTime"`
}

RegistrationInvite represents a shareable invite link for controlled registration

type Role

type Role struct {
	ID          string    `json:"id" gorm:"primaryKey"`
	Name        string    `json:"name" gorm:"not null;uniqueIndex"`
	Description string    `json:"description"`
	IsSystem    bool      `json:"is_system" gorm:"not null;default:false"`
	IsDefault   bool      `json:"is_default" gorm:"not null;default:false"`
	CreatedAt   time.Time `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt   time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}

Role represents a role in the RBAC system

type ScheduleType

type ScheduleType string

ScheduleType defines how the task is scheduled

const (
	ScheduleTypeCron     ScheduleType = "cron"     // Cron expression (e.g., "0 * * * *")
	ScheduleTypeInterval ScheduleType = "interval" // Fixed interval in seconds
	ScheduleTypeOnce     ScheduleType = "once"     // Run once at specific time
	ScheduleTypeEvent    ScheduleType = "event"    // Triggered by a server event
)

type ScheduledTask

type ScheduledTask struct {
	ID          string       `json:"id" gorm:"primaryKey"`
	ServerID    string       `json:"server_id" gorm:"not null;index;column:server_id"`
	Name        string       `json:"name" gorm:"not null"`
	Description string       `json:"description"`
	TaskType    TaskType     `json:"task_type" gorm:"not null;column:task_type"`
	Status      TaskStatus   `json:"status" gorm:"not null;default:enabled"`
	Schedule    ScheduleType `json:"schedule" gorm:"not null"`

	// Schedule configuration
	CronExpr      string                  `json:"cron_expr" gorm:"column:cron_expr"`                           // For cron schedule type
	IntervalSecs  int                     `json:"interval_secs" gorm:"column:interval_secs"`                   // For interval schedule type
	RunAt         *time.Time              `json:"run_at" gorm:"column:run_at"`                                 // For once schedule type
	EventTriggers []v1.TriggeredEventType `json:"event_triggers" gorm:"column:event_triggers;serializer:json"` // For event schedule type
	NextRun       *time.Time              `json:"next_run" gorm:"index;column:next_run"`                       // Computed next run time
	LastRun       *time.Time              `json:"last_run" gorm:"column:last_run"`                             // Last execution time
	Timezone      string                  `json:"timezone" gorm:"default:UTC"`                                 // Timezone for schedule

	// Task-specific configuration (JSON)
	Config string `json:"config" gorm:"type:text"` // JSON config based on task type

	// Execution settings
	Timeout       int  `json:"timeout" gorm:"default:300"`          // Timeout in seconds (default 5 min)
	RetryCount    int  `json:"retry_count" gorm:"default:0"`        // Number of retries on failure
	RetryDelay    int  `json:"retry_delay" gorm:"default:60"`       // Delay between retries in seconds
	RequireOnline bool `json:"require_online" gorm:"default:true"`  // Only run if server is online
	FailureNotify bool `json:"failure_notify" gorm:"default:false"` // Notify on failure (future feature)

	// Chain settings (MINE-142): tasks with the same ParentTaskID run in
	// StepOrder after the parent completes. A parent failure aborts the
	// chain unless the failed task has ContinueOnFailure.
	ParentTaskID      *string `json:"parent_task_id" gorm:"index;column:parent_task_id"`
	StepOrder         int     `json:"step_order" gorm:"default:0;column:step_order"`
	TimeOffsetSecs    int     `json:"time_offset_secs" gorm:"default:0;column:time_offset_secs"`
	ContinueOnFailure bool    `json:"continue_on_failure" gorm:"default:false;column:continue_on_failure"`

	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`

	Server *Server `json:"-" gorm:"foreignKey:ServerID;constraint:OnDelete:CASCADE"`
}

ScheduledTask represents a scheduled task for a server

type Server

type Server struct {
	ID              string       `json:"id" gorm:"primaryKey"`
	Name            string       `json:"name" gorm:"not null"`
	Description     string       `json:"description"`
	ModLoader       ModLoader    `json:"mod_loader" gorm:"not null"`
	MCVersion       string       `json:"mc_version" gorm:"not null;column:mc_version"`
	NodeID          string       `json:"node_id" gorm:"column:node_id;default:'default'"`
	ContainerID     string       `json:"container_id" gorm:"column:container_id"`
	Status          ServerStatus `json:"status" gorm:"not null"`
	Port            int          `json:"port"`
	ProxyPort       int          `json:"proxy_port" gorm:"column:proxy_port"`
	ProxyHostname   string       `json:"proxy_hostname" gorm:"column:proxy_hostname;uniqueIndex:idx_proxy_hostname_listener,where:proxy_hostname != ''"`
	ProxyListenerID string       `` // Which listener this server uses
	/* 126-byte string literal not displayed */
	MaxPlayers         int        `json:"max_players" gorm:"default:20;column:max_players"`
	Memory             int        `json:"memory" gorm:"default:4096"` // in MB (allocated) - IMPORTANT: This applies to the container's memory allocation first, then used to calc the JVM min/max for mc server proc inside w/ overhead
	CreatedAt          time.Time  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt          time.Time  `json:"updated_at" gorm:"autoUpdateTime"`
	LastStarted        *time.Time `json:"last_started" gorm:"column:last_started"`
	JavaVersion        string     `json:"java_version" gorm:"column:java_version"`
	DockerImage        string     `json:"docker_image" gorm:"column:docker_image"`
	DataPath           string     `json:"data_path" gorm:"not null;column:data_path"`
	Detached           bool       `json:"detached" gorm:"default:false;column:detached"`                      // Detach server container from Carbon Panel lifecycle (default: false)
	AutoStart          bool       `json:"auto_start" gorm:"default:false;column:auto_start"`                  // Start server when Carbon Panel starts (default: false)
	AutoHibernate      bool       `json:"auto_hibernate" gorm:"default:false;column:auto_hibernate"`          // Sleep/wake container on idle via cgroup freezer (MINE-18)
	IdleTimeoutMinutes int        `json:"idle_timeout_minutes" gorm:"default:10;column:idle_timeout_minutes"` // Minutes idle before auto-hibernating

	// Deep sleep: stop container on idle (zero RAM), boot on login via proxy (MINE-121).
	AutoDeepSleep           bool `json:"auto_deep_sleep" gorm:"default:false;column:auto_deep_sleep"`
	DeepSleepTimeoutMinutes int  `json:"deep_sleep_timeout_minutes" gorm:"default:30;column:deep_sleep_timeout_minutes"` // Minutes idle before deep sleep

	TPSCommand      string               `json:"tps_command" gorm:"column:tps_command"`                                     // The TPS command for this server (empty if not supported)
	AdditionalPorts []*v1.AdditionalPort `json:"additional_ports" gorm:"column:additional_ports;serializer:json"`           // Additional port configurations
	DockerOverrides *v1.DockerOverrides  `json:"docker_overrides" gorm:"column:docker_overrides;type:text;serializer:json"` // Docker container overrides

	// Runtime stats (not persisted to DB)
	MemoryUsage   float64 `json:"memory_usage" gorm:"-"`   // Current memory usage in MB
	CPUPercent    float64 `json:"cpu_percent" gorm:"-"`    // Current CPU usage percentage
	DiskUsage     int64   `json:"disk_usage" gorm:"-"`     // Total server data size in bytes
	DiskTotal     int64   `json:"disk_total" gorm:"-"`     // Total disk space available in bytes
	WorldSize     int64   `json:"world_size" gorm:"-"`     // World directory size in bytes
	PlayersOnline int     `json:"players_online" gorm:"-"` // Current players online
	TPS           float64 `json:"tps" gorm:"-"`            // Current TPS (20 is optimal)

	// SLP runtime stats (not persisted to DB)
	SLPAvailable    bool     `json:"slp_available" gorm:"-"`
	SLPLatencyMs    int64    `json:"slp_latency_ms" gorm:"-"`
	MOTD            string   `json:"motd" gorm:"-"`
	ServerVersion   string   `json:"server_version" gorm:"-"`
	ProtocolVersion int      `json:"protocol_version" gorm:"-"`
	PlayerSample    []string `json:"player_sample" gorm:"-"`
	MaxPlayersSLP   int      `json:"max_players_slp" gorm:"-"` // Actual from SLP (MaxPlayers field is config)
	Favicon         string   `json:"favicon" gorm:"-"`         // Base64 PNG from SLP
}

type ServerBlueprint

type ServerBlueprint struct {
	ID          string    `json:"id" gorm:"primaryKey"`
	Name        string    `json:"name" gorm:"not null;uniqueIndex"`
	Description string    `json:"description"`
	ModLoader   ModLoader `json:"mod_loader" gorm:"not null"`
	MCVersion   string    `json:"mc_version" gorm:"not null;column:mc_version"`
	DockerImage string    `json:"docker_image" gorm:"column:docker_image"` // override; empty = auto
	DefaultEnv  string    `json:"default_env" gorm:"type:text;column:default_env"`
	Builtin     bool      `json:"builtin" gorm:"default:false"`

	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}

ServerBlueprint is an importable server flavor seed (MINE-143, egg equivalent): loader + version + image + default env for one-click create.

type ServerConfig

type ServerConfig struct {
	ID        string    `json:"id" gorm:"primaryKey"`
	ServerID  string    `json:"server_id" gorm:"not null;index;column:server_id"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
	Server    *Server   `json:"-" gorm:"foreignKey:ServerID;constraint:OnDelete:CASCADE"`

	// JVM Configuration
	UID                    *int    `json:"uid" env:"UID" default:"1000" desc:"The linux user id to run as" input:"number" label:"User ID"`
	GID                    *int    `json:"gid" env:"GID" default:"1000" desc:"The linux group id to run as" input:"number" label:"Group ID"`
	Memory                 *string `` /* 129-byte string literal not displayed */
	InitMemory             *string `` /* 149-byte string literal not displayed */
	MaxMemory              *string `` /* 143-byte string literal not displayed */
	TZ                     *string `json:"tz" env:"TZ" default:"UTC" desc:"Timezone configuration" input:"text" label:"Timezone"`
	EnableRollingLogs      *bool   `` /* 152-byte string literal not displayed */
	EnableJMX              *bool   `json:"enableJmx" env:"ENABLE_JMX" default:"false" desc:"Enable remote JMX for profiling" input:"checkbox" label:"Enable JMX"`
	JMXHost                *string `json:"jmxHost" env:"JMX_HOST" default:"" desc:"IP/host running the Docker container for JMX" input:"text" label:"JMX Host"`
	UseAikarFlags          *bool   `` /* 152-byte string literal not displayed */
	UseGenerationalZgc     *bool   `` /* 184-byte string literal not displayed */
	UseMeowiceFlags        *bool   `` /* 159-byte string literal not displayed */
	UseMeowiceGraalVMFlags *bool   `` /* 169-byte string literal not displayed */
	JVMOpts                *string `json:"jvmOpts" env:"JVM_OPTS" default:"" desc:"General JVM options" input:"text" label:"JVM Options"`
	JVMXXOpts              *string `json:"jvmXxOpts" env:"JVM_XX_OPTS" default:"" desc:"JVM -XX options" input:"text" label:"JVM XX Options"`
	JVMDDOpts              *string `` /* 150-byte string literal not displayed */
	ExtraArgs              *string `json:"extraArgs" env:"EXTRA_ARGS" default:"" desc:"Arguments passed to the jar file" input:"text" label:"Extra Arguments"`
	LogTimestamp           *bool   `` /* 133-byte string literal not displayed */

	// Server Configuration
	Type                           *string `json:"type" env:"TYPE" default:"VANILLA" desc:"The server type" input:"text" label:"Server Type" system:"true"`
	CustomServer                   *string `` /* 139-byte string literal not displayed */
	CustomJarExec                  *string `` /* 179-byte string literal not displayed */
	EULA                           *string `` /* 136-byte string literal not displayed */
	Version                        *string `` /* 127-byte string literal not displayed */
	MOTD                           *string `json:"motd" env:"MOTD" default:"" desc:"Server log in message" input:"text" label:"Message of the Day"`
	Difficulty                     *string `` /* 135-byte string literal not displayed */
	Icon                           *string `json:"icon" env:"ICON" default:"" desc:"URL or file path for server icon" input:"text" label:"Server Icon"`
	OverrideIcon                   *bool   `` /* 131-byte string literal not displayed */
	MaxPlayers                     *int    `` /* 130-byte string literal not displayed */
	MaxWorldSize                   *int    `` /* 142-byte string literal not displayed */
	AllowNether                    *bool   `` /* 135-byte string literal not displayed */
	AnnouncePlayerAchievements     *bool   `` /* 173-byte string literal not displayed */
	EnableCommandBlock             *bool   `` /* 144-byte string literal not displayed */
	ForceGamemode                  *bool   `` /* 147-byte string literal not displayed */
	GenerateStructures             *bool   `` /* 152-byte string literal not displayed */
	Hardcore                       *bool   `` /* 131-byte string literal not displayed */
	SnooperEnabled                 *bool   `` /* 139-byte string literal not displayed */
	MaxBuildHeight                 *int    `` /* 129-byte string literal not displayed */
	SpawnAnimals                   *bool   `json:"spawnAnimals" env:"SPAWN_ANIMALS" default:"true" desc:"Allow animals to spawn" input:"checkbox" label:"Spawn Animals"`
	SpawnMonsters                  *bool   `` /* 127-byte string literal not displayed */
	SpawnNPCs                      *bool   `json:"spawnNpcs" env:"SPAWN_NPCS" default:"true" desc:"Allow villagers to spawn" input:"checkbox" label:"Spawn NPCs"`
	SpawnProtection                *int    `` /* 150-byte string literal not displayed */
	ViewDistance                   *int    `` /* 135-byte string literal not displayed */
	Seed                           *string `json:"seed" env:"SEED" default:"" desc:"World generation seed" input:"text" label:"World Seed"`
	Mode                           *string `` /* 131-byte string literal not displayed */
	PVP                            *bool   `json:"pvp" env:"PVP" default:"true" desc:"Enable player-vs-player mode" input:"checkbox" label:"Enable PVP"`
	LevelType                      *string `json:"levelType" env:"LEVEL_TYPE" default:"minecraft:default" desc:"World generation type" input:"text" label:"Level Type"`
	GeneratorSettings              *string `` /* 144-byte string literal not displayed */
	Level                          *string `json:"level" env:"LEVEL" default:"world" desc:"World save name" input:"text" label:"World Name"`
	OnlineMode                     *bool   `` /* 150-byte string literal not displayed */
	AllowFlight                    *bool   `` /* 138-byte string literal not displayed */
	ServerName                     *string `json:"serverName" env:"SERVER_NAME" default:"" desc:"The server name" input:"text" label:"Server Name"`
	ServerPort                     *int    `` /* 158-byte string literal not displayed */
	PlayerIdleTimeout              *int    `` /* 132-byte string literal not displayed */
	SyncChunkWrites                *bool   `` /* 129-byte string literal not displayed */
	EnableStatus                   *bool   `json:"enableStatus" env:"ENABLE_STATUS" default:"true" desc:"Enable server status" input:"checkbox" label:"Enable Status"`
	EntityBroadcastRangePercentage *int    `` /* 189-byte string literal not displayed */
	FunctionPermissionLevel        *int    `` /* 156-byte string literal not displayed */
	NetworkCompressionThreshold    *int    `` /* 174-byte string literal not displayed */
	OpPermissionLevel              *int    `` /* 132-byte string literal not displayed */
	PreventProxyConnections        *bool   `` /* 162-byte string literal not displayed */
	UseNativeTransport             *bool   `` /* 141-byte string literal not displayed */
	SimulationDistance             *int    `` /* 134-byte string literal not displayed */
	EnableQuery                    *bool   `` /* 128-byte string literal not displayed */
	QueryPort                      *int    `json:"queryPort" env:"QUERY_PORT" default:"25565" desc:"UDP port for GameSpy query" input:"number" label:"Query Port"`
	ServerPropertiesEscapeUnicode  *bool   `` /* 217-byte string literal not displayed */
	AcceptsTransfers               *bool   `` /* 152-byte string literal not displayed */
	BroadcastConsoleToOps          *bool   `` /* 165-byte string literal not displayed */
	BugReportLink                  *string `json:"bugReportLink" env:"BUG_REPORT_LINK" default:"" desc:"Custom bug report URL" input:"text" label:"Bug Report Link"`
	EnforceSecureProfile           *bool   `` /* 154-byte string literal not displayed */
	HideOnlinePlayers              *bool   `` /* 159-byte string literal not displayed */
	LogIPs                         *bool   `json:"logIps" env:"LOG_IPS" default:"true" desc:"Log connecting player IPs" input:"checkbox" label:"Log Player IPs"`
	MaxChainedNeighborUpdates      *int    `` /* 177-byte string literal not displayed */
	PauseWhenEmptySeconds          *int    `` /* 199-byte string literal not displayed */
	RateLimit                      *int    `json:"rateLimit" env:"RATE_LIMIT" default:"0" desc:"Rate limit in packets per second" input:"number" label:"Rate Limit"`
	RegionFileCompression          *string `` /* 162-byte string literal not displayed */
	ResourcePackID                 *string `json:"resourcePackId" env:"RESOURCE_PACK_ID" default:"" desc:"Custom resource pack ID" input:"text" label:"Resource Pack ID"`
	ResourcePackPrompt             *string `` /* 152-byte string literal not displayed */
	StatusHeartbeatInterval        *int    `` /* 161-byte string literal not displayed */
	ExecDirectly                   *bool   `` /* 165-byte string literal not displayed */
	StopServerAnnounceDelay        *int    `` /* 177-byte string literal not displayed */
	Proxy                          *string `json:"proxy" env:"PROXY" default:"" desc:"HTTP/HTTPS proxy URL" input:"text" label:"Proxy URL"`
	Console                        *bool   `` /* 132-byte string literal not displayed */
	GUI                            *bool   `json:"gui" env:"GUI" default:"true" desc:"GUI interface setting for older servers" input:"checkbox" label:"Enable GUI"`
	StopDuration                   *int    `` /* 134-byte string literal not displayed */
	SetupOnly                      *bool   `` /* 129-byte string literal not displayed */
	UseFlareFlags                  *bool   `` /* 149-byte string literal not displayed */
	UseSimdFlags                   *bool   `` /* 141-byte string literal not displayed */
	CustomServerProperties         *string `` /* 202-byte string literal not displayed */

	// Custom Resource Pack
	ResourcePack        *string `json:"resourcePack" env:"RESOURCE_PACK" default:"" desc:"Link to custom resource pack" input:"text" label:"Resource Pack URL"`
	ResourcePackSHA1    *string `` /* 140-byte string literal not displayed */
	ResourcePackEnforce *bool   `` /* 157-byte string literal not displayed */

	// Management Server passthrough for the itzg image env (MINE-127):
	// becoming the management server ourselves is aspirational and out of
	// scope — these fields must stay so existing configs keep working.
	ManagementServerAllowedOrigins      *string `` /* 193-byte string literal not displayed */
	ManagementServerEnabled             *bool   `` /* 170-byte string literal not displayed */
	ManagementServerHost                *string `` /* 160-byte string literal not displayed */
	ManagementServerPort                *int    `` /* 148-byte string literal not displayed */
	ManagementServerSecret              *string `` /* 179-byte string literal not displayed */
	ManagementServerTLSEnabled          *bool   `` /* 180-byte string literal not displayed */
	ManagementServerTLSKeystore         *string `` /* 162-byte string literal not displayed */
	ManagementServerTLSKeystorePassword *string `` /* 197-byte string literal not displayed */

	// Ops / Admins
	UserAPIProvider *string `` /* 160-byte string literal not displayed */
	Ops             *string `json:"ops" env:"OPS" default:"" desc:"Comma-separated list of operator usernames/UUIDs" input:"text" label:"Operators"`
	OpsFile         *string `json:"opsFile" env:"OPS_FILE" default:"" desc:"Path or URL to ops file" input:"text" label:"Ops File"`
	ExistingOpsFile *string `` /* 210-byte string literal not displayed */

	// Whitelist
	EnableWhitelist       *bool   `` /* 134-byte string literal not displayed */
	Whitelist             *string `` /* 129-byte string literal not displayed */
	WhitelistFile         *string `` /* 130-byte string literal not displayed */
	OverrideWhitelist     *bool   `` /* 153-byte string literal not displayed */
	ExistingWhitelistFile *string `` /* 234-byte string literal not displayed */
	EnforceWhitelist      *bool   `` /* 151-byte string literal not displayed */

	// RCON
	EnableRCON             *bool   `json:"enableRcon" env:"ENABLE_RCON" default:"true" desc:"Enable RCON support" input:"checkbox" label:"Enable RCON"`
	RCONPassword           *string `` /* 144-byte string literal not displayed */
	RCONPort               *int    `json:"rconPort" env:"RCON_PORT" default:"25575" desc:"RCON port" input:"number" label:"RCON Port"`
	BroadcastRCONToOps     *bool   `` /* 145-byte string literal not displayed */
	RCONCmdsStartup        *string `` /* 151-byte string literal not displayed */
	RCONCmdsOnConnect      *string `` /* 158-byte string literal not displayed */
	RCONCmdsFirstConnect   *string `` /* 176-byte string literal not displayed */
	RCONCmdsOnDisconnect   *string `` /* 170-byte string literal not displayed */
	RCONCmdsLastDisconnect *string `` /* 184-byte string literal not displayed */

	// Forge Configuration
	ForgeVersion      *string `` /* 126-byte string literal not displayed */
	ForgeInstaller    *string `` /* 137-byte string literal not displayed */
	ForgeInstallerURL *string `` /* 141-byte string literal not displayed */

	// CurseForge
	CFAPIKey                  *string `` /* 199-byte string literal not displayed */
	CFAPIKeyFile              *string `` /* 147-byte string literal not displayed */
	CFPageURL                 *string `` /* 237-byte string literal not displayed */
	CFSlug                    *string `` /* 145-byte string literal not displayed */
	CFFileID                  *string `` /* 168-byte string literal not displayed */
	CFModpackZip              *string `` /* 144-byte string literal not displayed */
	CFFilenameMatcher         *string `` /* 153-byte string literal not displayed */
	CFExcludeIncludeFile      *string `` /* 168-byte string literal not displayed */
	CFExcludeMods             *string `` /* 160-byte string literal not displayed */
	CFForceIncludeMods        *string `` /* 177-byte string literal not displayed */
	CFForceSynchronize        *bool   `` /* 180-byte string literal not displayed */
	CFSetLevelFrom            *string `` /* 151-byte string literal not displayed */
	CFParallelDownloads       *int    `` /* 174-byte string literal not displayed */
	CFOverridesSkipExisting   *bool   `` /* 179-byte string literal not displayed */
	CFForceReinstallModloader *bool   `` /* 206-byte string literal not displayed */

	// Modrinth
	ModrinthModpack                    *string `` /* 167-byte string literal not displayed */
	ModrinthModpackVersionType         *string `` /* 195-byte string literal not displayed */
	ModrinthVersion                    *string `` /* 157-byte string literal not displayed */
	ModrinthLoader                     *string `` /* 157-byte string literal not displayed */
	ModrinthIgnoreMissingFiles         *string `` /* 191-byte string literal not displayed */
	ModrinthExcludeFiles               *string `` /* 174-byte string literal not displayed */
	ModrinthForceIncludeFiles          *string `` /* 197-byte string literal not displayed */
	ModrinthForceSynchronize           *bool   `` /* 171-byte string literal not displayed */
	ModrinthDefaultExcludeIncludes     *string `` /* 197-byte string literal not displayed */
	ModrinthOverridesExclusions        *string `` /* 207-byte string literal not displayed */
	ModrinthProjects                   *string `` /* 167-byte string literal not displayed */
	ModrinthDownloadDependencies       *string `` /* 200-byte string literal not displayed */
	ModrinthProjectsDefaultVersionType *string `` /* 218-byte string literal not displayed */
	VersionFromModrinthProjects        *bool   `` /* 212-byte string literal not displayed */
	ModrinthToken                      *string `` /* 162-byte string literal not displayed */
	ModrinthUserAgent                  *string `` /* 160-byte string literal not displayed */
	PackwizURL                         *string `` /* 137-byte string literal not displayed */
}

type ServerSnapshot

type ServerSnapshot struct {
	ID        string    `json:"id" gorm:"primaryKey"`
	ServerID  string    `json:"server_id" gorm:"not null;index;column:server_id"`
	Name      string    `json:"name" gorm:"not null"`
	Reason    string    `json:"reason" gorm:"column:reason"`
	FilePath  string    `json:"file_path" gorm:"not null;column:file_path"`
	SizeBytes int64     `json:"size_bytes" gorm:"column:size_bytes"`
	FileCount int       `json:"file_count" gorm:"column:file_count"`
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;index"`
	Server    *Server   `json:"-" gorm:"foreignKey:ServerID;constraint:OnDelete:CASCADE"`
}

ServerSnapshot represents a volume snapshot taken before modpack updates or upgrades (MINE-23)

type ServerStatus

type ServerStatus string
const (
	StatusStopped   ServerStatus = "stopped"
	StatusStarting  ServerStatus = "starting"
	StatusRunning   ServerStatus = "running"
	StatusStopping  ServerStatus = "stopping"
	StatusError     ServerStatus = "error"
	StatusUnhealthy ServerStatus = "unhealthy"
	StatusCreating  ServerStatus = "creating" // Container is being created/image pulled
	StatusPaused    ServerStatus = "paused"   // Container hibernated via cgroup freezer

	// StatusDeepSleep: container stopped via deep sleep; proxy retains route, wakes on login (MINE-121).
	StatusDeepSleep ServerStatus = "deepsleep"
)

type ServerSubuser

type ServerSubuser struct {
	ServerID    string `json:"server_id" gorm:"primaryKey;column:server_id"`
	UserID      string `json:"user_id" gorm:"primaryKey;column:user_id"`
	Permissions string `json:"permissions" gorm:"type:text"` // JSON array of "resource.action"

	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
}

ServerSubuser grants a non-admin user scoped permissions on one server (MINE-139). Permissions holds "resource.action" strings, e.g. "servers.start". Grants never exceed what the panel offers; admins bypass.

type Session

type Session struct {
	ID        string    `json:"id" gorm:"primaryKey"`
	UserID    string    `json:"user_id" gorm:"not null;index;column:user_id"`
	Token     string    `json:"-" gorm:"not null;uniqueIndex"`
	ExpiresAt time.Time `json:"expires_at" gorm:"not null;index"`
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
	User      *User     `json:"user,omitempty" gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`
}

Session represents an active user session

type StagedApplyMode

type StagedApplyMode string

StagedApplyMode defines when a staged config change takes effect.

const (
	StagedApplyOnRestart StagedApplyMode = "on_restart" // applied on next server restart
	StagedApplyScheduled StagedApplyMode = "scheduled"  // applied once its cron schedule fires
)

type StagedConfigChange

type StagedConfigChange struct {
	ID              string          `json:"id" gorm:"primaryKey"`
	ServerID        string          `json:"server_id" gorm:"not null;index;column:server_id"`
	Payload         string          `json:"payload" gorm:"type:text;column:payload"`                             // JSON diff vs live config
	PreviousPayload string          `json:"previous_payload,omitempty" gorm:"type:text;column:previous_payload"` // JSON diff of previous values before apply (SCH-1)
	ApplyMode       StagedApplyMode `json:"apply_mode" gorm:"not null;column:apply_mode"`
	CronExpr        string          `json:"cron_expr" gorm:"column:cron_expr"` // required when ApplyMode == scheduled
	Status          StagedStatus    `json:"status" gorm:"not null;default:staged;index"`
	CreatedAt       time.Time       `json:"created_at" gorm:"autoCreateTime;index"`
	AppliedAt       *time.Time      `json:"applied_at,omitempty" gorm:"column:applied_at"`
	RolledBackAt    *time.Time      `json:"rolled_back_at,omitempty" gorm:"column:rolled_back_at"`
	Server          *Server         `json:"-" gorm:"foreignKey:ServerID;constraint:OnDelete:CASCADE"`
}

StagedConfigChange records a config change made to an instance regardless of its operational state. Payload holds the diff vs the live ServerConfig at stage time (JSON object of ServerConfig json field names to values). MVP scope: one-shot semantics — a "scheduled" change applies the first time its cron expression fires after creation, then flips to "applied". Remaining work (see staged_config.go): recurring schedules, per-field conflict detection when the live config moved since staging, RBAC-gated approvals, and audit linkage.

type StagedStatus

type StagedStatus string

StagedStatus defines the lifecycle state of a staged config change.

const (
	StagedStatusStaged     StagedStatus = "staged"
	StagedStatusApplied    StagedStatus = "applied"
	StagedStatusDiscarded  StagedStatus = "discarded"
	StagedStatusRolledBack StagedStatus = "rolled_back"
)

type Store

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

func NewSQLiteStore

func NewSQLiteStore(cfg *config.Config) (*Store, error)

func (*Store) AddMod

func (s *Store) AddMod(ctx context.Context, mod *Mod) error

Mod operations

func (*Store) AddModpackFavorite

func (s *Store) AddModpackFavorite(ctx context.Context, modpackID string) error

Modpack Favorite operations

func (*Store) ApplyStagedConfigChange

func (s *Store) ApplyStagedConfigChange(ctx context.Context, id string) (*StagedConfigChange, error)

ApplyStagedConfigChange merges a staged diff into the live ServerConfig and flips the record to applied. Callers decide when to invoke it (restart hook or cron tick); container recreation stays the caller's responsibility.

func (*Store) AssignRole

func (s *Store) AssignRole(ctx context.Context, userID, roleName, source string) error

UserRole operations

func (*Store) BackupTo

func (s *Store) BackupTo(ctx context.Context, dest string) error

BackupTo writes a consistent snapshot of the panel database to dest. The source stays open and usable. A failed integrity check removes only the new file and leaves any previous snapshot at dest in place.

func (*Store) CheckModpackInUse

func (s *Store) CheckModpackInUse(ctx context.Context, modpackID string) ([]*Server, error)

Checks if any servers are using the specified modpack

func (*Store) CheckPortAvailability

func (s *Store) CheckPortAvailability(ctx context.Context, hostPort int, protocol string, proxyEnabled bool, hostname string, excludeModuleID string) (*PortConflict, error)

CheckPortAvailability checks if a port can be used by a module, considering: - Non-proxied ports: exclusive (Docker binds to host) - Proxied TCP: can share if different hostname (TCP proxy routes by hostname) - Proxied UDP: exclusive (UDP proxy only supports one route per port)

Returns nil if port is available, or a PortConflict if not. excludeModuleID allows excluding the current module when updating.

func (*Store) CleanAllSessions

func (s *Store) CleanAllSessions(ctx context.Context) error

CleanAllSessions deletes all sessions (used when JWT secret changes).

func (*Store) CleanExpiredSessions

func (s *Store) CleanExpiredSessions(ctx context.Context) error

func (*Store) CleanOldTaskExecutions

func (s *Store) CleanOldTaskExecutions(ctx context.Context, olderThan time.Time, keepMinimum int) error

func (*Store) ClearEphemeralConfigFields

func (s *Store) ClearEphemeralConfigFields(ctx context.Context, serverID string) error

ClearEphemeralConfigFields clears all ephemeral configuration fields

func (*Store) Close

func (s *Store) Close() error

func (*Store) CountUsers

func (s *Store) CountUsers(ctx context.Context) (int64, error)

func (*Store) CreateAPIToken

func (s *Store) CreateAPIToken(ctx context.Context, token *APIToken) error

APIToken operations

func (*Store) CreateBackupRecord

func (s *Store) CreateBackupRecord(ctx context.Context, rec *BackupRecord) error

CreateBackupRecord inserts a backup row.

func (*Store) CreateDefaultServerConfig

func (s *Store) CreateDefaultServerConfig(serverID string) *ServerConfig

func (*Store) CreateModule

func (s *Store) CreateModule(ctx context.Context, module *Module) error

Module operations

func (*Store) CreateModuleTemplate

func (s *Store) CreateModuleTemplate(ctx context.Context, template *ModuleTemplate) error

ModuleTemplate operations

func (*Store) CreateNode

func (s *Store) CreateNode(ctx context.Context, node *Node) error

func (*Store) CreateProxyListener

func (s *Store) CreateProxyListener(ctx context.Context, listener *ProxyListener) error

func (*Store) CreateRegistrationInvite

func (s *Store) CreateRegistrationInvite(ctx context.Context, invite *RegistrationInvite) error

RegistrationInvite operations

func (*Store) CreateRole

func (s *Store) CreateRole(ctx context.Context, role *Role) error

func (*Store) CreateScheduledTask

func (s *Store) CreateScheduledTask(ctx context.Context, task *ScheduledTask) error

ScheduledTask operations

func (*Store) CreateServer

func (s *Store) CreateServer(ctx context.Context, server *Server) error

Server operations

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, session *Session) error

Session operations

func (*Store) CreateSnapshot

func (s *Store) CreateSnapshot(ctx context.Context, snapshot *ServerSnapshot) error

CreateSnapshot stores a new server snapshot record

func (*Store) CreateTaskExecution

func (s *Store) CreateTaskExecution(ctx context.Context, execution *TaskExecution) error

TaskExecution operations

func (*Store) CreateUser

func (s *Store) CreateUser(ctx context.Context, user *User) error

User operations

func (*Store) DB

func (s *Store) DB() *gorm.DB

func (*Store) DeleteAPIToken

func (s *Store) DeleteAPIToken(ctx context.Context, id, userID string) error

func (*Store) DeleteAPITokenByID

func (s *Store) DeleteAPITokenByID(ctx context.Context, id string) error

func (*Store) DeleteBackupRecord

func (s *Store) DeleteBackupRecord(ctx context.Context, id string) error

DeleteBackupRecord removes a backup row.

func (*Store) DeleteIndexedModpack

func (s *Store) DeleteIndexedModpack(ctx context.Context, modpackID string) error

Deletes a modpack and all related records

func (*Store) DeleteMod

func (s *Store) DeleteMod(ctx context.Context, id string) error

func (*Store) DeleteModule

func (s *Store) DeleteModule(ctx context.Context, id string) error

func (*Store) DeleteModuleTemplate

func (s *Store) DeleteModuleTemplate(ctx context.Context, id string) error

func (*Store) DeleteNode

func (s *Store) DeleteNode(ctx context.Context, id string) error

func (*Store) DeleteProxyListener

func (s *Store) DeleteProxyListener(ctx context.Context, id string) error

func (*Store) DeleteRegistrationInvite

func (s *Store) DeleteRegistrationInvite(ctx context.Context, id string) error

func (*Store) DeleteRole

func (s *Store) DeleteRole(ctx context.Context, id string) error

func (*Store) DeleteScheduledTask

func (s *Store) DeleteScheduledTask(ctx context.Context, id string) error

func (*Store) DeleteServer

func (s *Store) DeleteServer(ctx context.Context, id string) error

func (*Store) DeleteSession

func (s *Store) DeleteSession(ctx context.Context, token string) error

func (*Store) DeleteSnapshot

func (s *Store) DeleteSnapshot(ctx context.Context, id string) error

DeleteSnapshot removes a snapshot record from the database

func (*Store) DeleteTaskExecutions

func (s *Store) DeleteTaskExecutions(ctx context.Context, taskID string) error

func (*Store) DeleteUser

func (s *Store) DeleteUser(ctx context.Context, id string) error

func (*Store) DeleteUserSessionsExcept

func (s *Store) DeleteUserSessionsExcept(ctx context.Context, userID, exceptToken string) error

DeleteUserSessionsExcept removes every stored session for userID, keeping the session identified by exceptToken when it is non-empty. Used after a password change so other sessions cannot outlive the credential rotation.

func (*Store) DiscardStagedConfigChange

func (s *Store) DiscardStagedConfigChange(ctx context.Context, id string) error

DiscardStagedConfigChange moves a staged record to discarded.

func (*Store) EnsureDefaultNode

func (s *Store) EnsureDefaultNode(ctx context.Context) (*Node, error)

EnsureDefaultNode is retained for backwards compatibility but no longer seeds a phantom "default" node. Fresh installs start with zero nodes and operators register Docker daemons explicitly via the Nodes settings UI. It returns the existing local node if one is present, and an error otherwise so callers surface "no nodes registered" instead of silently falling back to a node that does not exist.

func (*Store) FailOrphanedTaskExecutions

func (s *Store) FailOrphanedTaskExecutions(ctx context.Context, reason string) (int64, error)

FailOrphanedTaskExecutions marks all task executions currently recorded in the 'running' state as failed with the given reason. This is invoked during scheduler startup to resolve executions left dangling by an unexpected daemon crash or host reboot.

func (*Store) FindAvailableListenerPort

func (s *Store) FindAvailableListenerPort(ctx context.Context) (int, error)

Finds first available port for a proxy listener

func (*Store) GetAPITokenByHash

func (s *Store) GetAPITokenByHash(ctx context.Context, hash string) (*APIToken, error)

func (*Store) GetBackupRecord

func (s *Store) GetBackupRecord(ctx context.Context, id string) (*BackupRecord, error)

GetBackupRecord fetches one backup by ID.

func (*Store) GetBlueprint

func (s *Store) GetBlueprint(ctx context.Context, id string) (*ServerBlueprint, error)

GetBlueprint returns one blueprint by ID.

func (*Store) GetDefaultRoles

func (s *Store) GetDefaultRoles(ctx context.Context) ([]*Role, error)

func (*Store) GetGlobalSettings

func (s *Store) GetGlobalSettings(ctx context.Context) (*ServerConfig, bool, error)

func (*Store) GetIndexedModpack

func (s *Store) GetIndexedModpack(ctx context.Context, id string) (*IndexedModpack, error)

func (*Store) GetIndexedModpackFiles

func (s *Store) GetIndexedModpackFiles(ctx context.Context, modpackID string) ([]*IndexedModpackFile, error)

func (*Store) GetMod

func (s *Store) GetMod(ctx context.Context, id string) (*Mod, error)

func (*Store) GetModpackBySlug

func (s *Store) GetModpackBySlug(ctx context.Context, slug string) (*IndexedModpack, error)

func (*Store) GetModpackByWebsiteURL

func (s *Store) GetModpackByWebsiteURL(ctx context.Context, url string) (*IndexedModpack, error)

func (*Store) GetModule

func (s *Store) GetModule(ctx context.Context, id string) (*Module, error)

func (*Store) GetModuleByContainerID

func (s *Store) GetModuleByContainerID(ctx context.Context, containerID string) (*Module, error)

func (*Store) GetModuleByHostPort

func (s *Store) GetModuleByHostPort(ctx context.Context, port int) (*Module, error)

GetModuleByHostPort finds a module that uses the specified host port

func (*Store) GetModuleTemplate

func (s *Store) GetModuleTemplate(ctx context.Context, id string) (*ModuleTemplate, error)

func (*Store) GetModuleTemplateByName

func (s *Store) GetModuleTemplateByName(ctx context.Context, name string) (*ModuleTemplate, error)

func (*Store) GetNode

func (s *Store) GetNode(ctx context.Context, id string) (*Node, error)

func (*Store) GetNodeRunningMemoryMB

func (s *Store) GetNodeRunningMemoryMB(ctx context.Context, nodeID string) (int64, error)

GetNodeRunningMemoryMB returns the sum of memory for all active (running or starting) servers on a node.

func (*Store) GetNodeStats

func (s *Store) GetNodeStats(ctx context.Context, nodeID string) (allocatedMemMB int64, serverCount int, runningCount int, err error)

func (*Store) GetProxyConfig

func (s *Store) GetProxyConfig(ctx context.Context) (*ProxyConfig, bool, error)

ProxyConfig operations

func (*Store) GetProxyListener

func (s *Store) GetProxyListener(ctx context.Context, id string) (*ProxyListener, error)

func (*Store) GetProxyListenerByPort

func (s *Store) GetProxyListenerByPort(ctx context.Context, port int) (*ProxyListener, error)

func (*Store) GetProxyListeners

func (s *Store) GetProxyListeners(ctx context.Context) ([]*ProxyListener, error)

ProxyListener operations

func (*Store) GetRegistrationInvite

func (s *Store) GetRegistrationInvite(ctx context.Context, id string) (*RegistrationInvite, error)

func (*Store) GetRegistrationInviteByCode

func (s *Store) GetRegistrationInviteByCode(ctx context.Context, code string) (*RegistrationInvite, error)

func (*Store) GetRole

func (s *Store) GetRole(ctx context.Context, id string) (*Role, error)

func (*Store) GetScheduledTask

func (s *Store) GetScheduledTask(ctx context.Context, id string) (*ScheduledTask, error)

func (*Store) GetServer

func (s *Store) GetServer(ctx context.Context, id string) (*Server, error)

func (*Store) GetServerByContainerID

func (s *Store) GetServerByContainerID(ctx context.Context, containerID string) (*Server, error)

GetServerByContainerID reverse-looks-up the Server that owns the given Docker container ID. Used during identity-resolution recovery (MINE-103) to determine whether a re-discovered container is already tracked by a different server record before adopting it.

func (*Store) GetServerByPort

func (s *Store) GetServerByPort(ctx context.Context, port int) (*Server, error)

func (*Store) GetServerConfig

func (s *Store) GetServerConfig(ctx context.Context, serverID string) (*ServerConfig, error)

Server config operations

func (*Store) GetSession

func (s *Store) GetSession(ctx context.Context, token string) (*Session, error)

func (*Store) GetSnapshot

func (s *Store) GetSnapshot(ctx context.Context, id string) (*ServerSnapshot, error)

GetSnapshot retrieves a server snapshot by ID

func (*Store) GetStagedConfigChange

func (s *Store) GetStagedConfigChange(ctx context.Context, id string) (*StagedConfigChange, error)

GetStagedConfigChange fetches a single staged record by id.

func (*Store) GetSystemSetting

func (s *Store) GetSystemSetting(ctx context.Context, key string) (string, error)

func (*Store) GetTaskExecution

func (s *Store) GetTaskExecution(ctx context.Context, id string) (*TaskExecution, error)

func (*Store) GetUser

func (s *Store) GetUser(ctx context.Context, id string) (*User, error)

func (*Store) GetUserByOIDCSubject

func (s *Store) GetUserByOIDCSubject(ctx context.Context, subject string) (*User, error)

func (*Store) GetUserByUsernameAndProvider

func (s *Store) GetUserByUsernameAndProvider(ctx context.Context, username, provider string) (*User, error)

func (*Store) GetUserRoleNames

func (s *Store) GetUserRoleNames(ctx context.Context, userID string) ([]string, error)

func (*Store) HasRunningExecution

func (s *Store) HasRunningExecution(ctx context.Context, taskID string) (bool, error)

HasRunningExecution reports whether an active execution is recorded as running in the database for the given task (SCH-5).

func (*Store) IncrementInviteUseCount

func (s *Store) IncrementInviteUseCount(ctx context.Context, id string) error

func (*Store) IsModpackFavorited

func (s *Store) IsModpackFavorited(ctx context.Context, modpackID string) (bool, error)

func (*Store) ListAPITokensByUser

func (s *Store) ListAPITokensByUser(ctx context.Context, userID string) ([]APIToken, error)

func (*Store) ListAllScheduledTasks

func (s *Store) ListAllScheduledTasks(ctx context.Context) ([]*ScheduledTask, error)

func (*Store) ListAutoStartModules

func (s *Store) ListAutoStartModules(ctx context.Context) ([]*Module, error)

func (*Store) ListBackupRecords

func (s *Store) ListBackupRecords(ctx context.Context, serverID string, limit int) ([]*BackupRecord, error)

ListBackupRecords returns newest-first backups for a server.

func (*Store) ListBlueprints

func (s *Store) ListBlueprints(ctx context.Context) ([]*ServerBlueprint, error)

ListBlueprints returns all blueprints, builtins first.

func (*Store) ListBuiltinModuleTemplates

func (s *Store) ListBuiltinModuleTemplates(ctx context.Context) ([]*ModuleTemplate, error)

func (*Store) ListChildTasks

func (s *Store) ListChildTasks(ctx context.Context, parentID string) ([]*ScheduledTask, error)

ListChildTasks returns enabled chain steps of a parent in step order (MINE-142).

func (*Store) ListDueScheduledStagedChanges

func (s *Store) ListDueScheduledStagedChanges(ctx context.Context, now time.Time) ([]*StagedConfigChange, error)

ListDueScheduledStagedChanges returns staged + scheduled records whose cron expression has fired at least once since creation and which are therefore due for a one-shot apply. Malformed expressions are skipped.

func (*Store) ListDueScheduledTasks

func (s *Store) ListDueScheduledTasks(ctx context.Context, before time.Time) ([]*ScheduledTask, error)

func (*Store) ListEventTriggeredTasks

func (s *Store) ListEventTriggeredTasks(ctx context.Context, serverID string, eventType v1.TriggeredEventType) ([]*ScheduledTask, error)

ListEventTriggeredTasks returns all enabled tasks subscribed to the given event for a server. EventTriggers is stored as a JSON array, so we filter in Go.

func (*Store) ListFavoriteModpacks

func (s *Store) ListFavoriteModpacks(ctx context.Context) ([]*IndexedModpack, error)

func (*Store) ListIndexedModpacks

func (s *Store) ListIndexedModpacks(ctx context.Context, offset, limit int) ([]*IndexedModpack, int64, error)

func (*Store) ListModuleTemplates

func (s *Store) ListModuleTemplates(ctx context.Context) ([]*ModuleTemplate, error)

func (*Store) ListModules

func (s *Store) ListModules(ctx context.Context) ([]*Module, error)

func (*Store) ListModulesByNode

func (s *Store) ListModulesByNode(ctx context.Context, nodeID string) ([]*Module, error)

func (*Store) ListModulesByTemplate

func (s *Store) ListModulesByTemplate(ctx context.Context, templateID string) ([]*Module, error)

func (*Store) ListModulesFollowingServerLifecycle

func (s *Store) ListModulesFollowingServerLifecycle(ctx context.Context, serverID string) ([]*Module, error)

func (*Store) ListNodes

func (s *Store) ListNodes(ctx context.Context) ([]*Node, error)

func (*Store) ListNodesWithStats

func (s *Store) ListNodesWithStats(ctx context.Context) ([]*Node, error)

func (*Store) ListRegistrationInvites

func (s *Store) ListRegistrationInvites(ctx context.Context) ([]*RegistrationInvite, error)

func (*Store) ListRoles

func (s *Store) ListRoles(ctx context.Context) ([]*Role, error)

func (*Store) ListScheduledTasks

func (s *Store) ListScheduledTasks(ctx context.Context, serverID string) ([]*ScheduledTask, error)

func (*Store) ListServerMods

func (s *Store) ListServerMods(ctx context.Context, serverID string) ([]*Mod, error)

func (*Store) ListServerModules

func (s *Store) ListServerModules(ctx context.Context, serverID string) ([]*Module, error)

func (*Store) ListServerTaskExecutions

func (s *Store) ListServerTaskExecutions(ctx context.Context, serverID string, limit int) ([]*TaskExecution, error)

func (*Store) ListServers

func (s *Store) ListServers(ctx context.Context) ([]*Server, error)

func (*Store) ListServersByNode

func (s *Store) ListServersByNode(ctx context.Context, nodeID string) ([]*Server, error)

func (*Store) ListSnapshots

func (s *Store) ListSnapshots(ctx context.Context, serverID string) ([]*ServerSnapshot, error)

ListSnapshots retrieves all snapshots for a server, newest first

func (*Store) ListStagedConfigChanges

func (s *Store) ListStagedConfigChanges(ctx context.Context, serverID string, status StagedStatus) ([]*StagedConfigChange, error)

ListStagedConfigChanges returns staged records for a server, newest first. Pass an empty status to list every status.

func (*Store) ListSubusers

func (s *Store) ListSubusers(ctx context.Context, serverID string) ([]*ServerSubuser, error)

ListSubusers returns all grants on a server.

func (*Store) ListTaskExecutions

func (s *Store) ListTaskExecutions(ctx context.Context, taskID string, limit int) ([]*TaskExecution, error)

func (*Store) ListUsers

func (s *Store) ListUsers(ctx context.Context) ([]*User, error)

func (*Store) Migrate

func (s *Store) Migrate() error

func (*Store) RemoveModpackFavorite

func (s *Store) RemoveModpackFavorite(ctx context.Context, modpackID string) error

func (*Store) RemoveSubuser

func (s *Store) RemoveSubuser(ctx context.Context, serverID, userID string) error

RemoveSubuser revokes a user's grant on a server.

func (*Store) ResetAllUsers

func (s *Store) ResetAllUsers(ctx context.Context) error

ResetAllUsers deletes all sessions, API tokens, user roles, registration invites, and users.

func (*Store) RollbackStagedConfigChange

func (s *Store) RollbackStagedConfigChange(ctx context.Context, id string) (*StagedConfigChange, error)

RollbackStagedConfigChange reverts an applied staged config change by restoring the previous values of all modified fields back onto the live ServerConfig, and marking the staged record as rolled_back (SCH-1).

func (*Store) RunPanelBackup

func (s *Store) RunPanelBackup(ctx context.Context, dir string, keep int, now time.Time) (string, error)

RunPanelBackup writes today's snapshot into dir and then drops older daily files beyond keep. keep < 1 retains every snapshot.

func (*Store) SaveBlueprint

func (s *Store) SaveBlueprint(ctx context.Context, bp *ServerBlueprint) error

SaveBlueprint upserts a blueprint by ID.

func (*Store) SaveProxyConfig

func (s *Store) SaveProxyConfig(ctx context.Context, config *ProxyConfig) error

func (*Store) SaveServerConfig

func (s *Store) SaveServerConfig(ctx context.Context, config *ServerConfig) error

func (*Store) SearchIndexedModpacks

func (s *Store) SearchIndexedModpacks(ctx context.Context, query string, gameVersion string, modLoader string, indexer string, offset, limit int) ([]*IndexedModpack, int64, error)

func (*Store) SeedDefaultNode

func (s *Store) SeedDefaultNode() error

func (*Store) SeedGlobalSettings

func (s *Store) SeedGlobalSettings() error

func (*Store) SeedSystemRoles

func (s *Store) SeedSystemRoles() error

Role operations

func (*Store) SetBackupLocked

func (s *Store) SetBackupLocked(ctx context.Context, id string, locked bool) error

SetBackupLocked toggles the sticky flag.

func (*Store) SetBackupRemoteKey

func (s *Store) SetBackupRemoteKey(ctx context.Context, id, key string) error

SetBackupRemoteKey records the S3 object key.

func (*Store) SetBackupStatus

func (s *Store) SetBackupStatus(ctx context.Context, id, status string) error

SetBackupStatus updates the status field.

func (*Store) SetSystemSetting

func (s *Store) SetSystemSetting(ctx context.Context, key, value string) error

func (*Store) StageConfigChange

func (s *Store) StageConfigChange(ctx context.Context, serverID string, changes map[string]any, mode StagedApplyMode, cronExpr string) (*StagedConfigChange, error)

StageConfigChange records changes as a diff vs the live config. It works regardless of the instance's operational state — nothing is applied here.

func (*Store) SubuserPermissions

func (s *Store) SubuserPermissions(ctx context.Context, serverID, userID string) []string

SubuserPermissions returns the granted "resource.action" list, or nil.

func (*Store) SyncServerConfigWithServer

func (s *Store) SyncServerConfigWithServer(ctx context.Context, server *Server) error

SyncServerConfigWithServer updates system fields in ServerConfig based on Server settings

func (*Store) UnassignRole

func (s *Store) UnassignRole(ctx context.Context, userID, roleName string) error

func (*Store) UpdateAPITokenLastUsed

func (s *Store) UpdateAPITokenLastUsed(ctx context.Context, id string) error

func (*Store) UpdateGlobalSettings

func (s *Store) UpdateGlobalSettings(ctx context.Context, config *ServerConfig) error

func (*Store) UpdateMod

func (s *Store) UpdateMod(ctx context.Context, mod *Mod) error

func (*Store) UpdateModule

func (s *Store) UpdateModule(ctx context.Context, module *Module) error

func (*Store) UpdateModuleContainerID

func (s *Store) UpdateModuleContainerID(ctx context.Context, id string, containerID string) error

UpdateModuleContainerID updates only the container_id column for a module, avoiding the full-row clobber that UpdateModule's Save performs.

func (*Store) UpdateModuleTemplate

func (s *Store) UpdateModuleTemplate(ctx context.Context, template *ModuleTemplate) error

func (*Store) UpdateNode

func (s *Store) UpdateNode(ctx context.Context, node *Node) error

func (*Store) UpdateProxyListener

func (s *Store) UpdateProxyListener(ctx context.Context, listener *ProxyListener) error

func (*Store) UpdateRole

func (s *Store) UpdateRole(ctx context.Context, role *Role) error

func (*Store) UpdateScheduledTask

func (s *Store) UpdateScheduledTask(ctx context.Context, task *ScheduledTask) error

func (*Store) UpdateServer

func (s *Store) UpdateServer(ctx context.Context, server *Server) error

func (*Store) UpdateServerConfig

func (s *Store) UpdateServerConfig(ctx context.Context, config *ServerConfig) error

func (*Store) UpdateServerConfigMemory

func (s *Store) UpdateServerConfigMemory(ctx context.Context, serverID string, memory int) error

UpdateServerConfigMemory updates memory settings in ServerConfig

func (*Store) UpdateServerContainerID

func (s *Store) UpdateServerContainerID(ctx context.Context, id string, containerID string) error

UpdateServerContainerID updates only the container_id column for a server, avoiding the full-row clobber that UpdateServer's Save performs. This prevents a stale in-memory *Server (e.g. held by a background reader) from overwriting a ContainerID change made concurrently by another goroutine.

func (*Store) UpdateServerFields

func (s *Store) UpdateServerFields(ctx context.Context, id string, fields map[string]interface{}) error

UpdateServerFields performs a targeted multi-column update for a server, updating only the columns present in fields. This avoids the full-row clobber that UpdateServer's Save performs, which is important when the caller only has a partial view of the server (e.g. read earlier and possibly stale by the time the write happens).

func (*Store) UpdateServerStatus

func (s *Store) UpdateServerStatus(ctx context.Context, id string, status ServerStatus) error

UpdateServerStatus updates only the status column for a server, avoiding the full-row clobber that UpdateServer's Save performs.

func (*Store) UpdateTaskExecution

func (s *Store) UpdateTaskExecution(ctx context.Context, execution *TaskExecution) error

func (*Store) UpdateTaskNextRun

func (s *Store) UpdateTaskNextRun(ctx context.Context, taskID string, nextRun *time.Time, lastRun *time.Time) error

func (*Store) UpdateUser

func (s *Store) UpdateUser(ctx context.Context, user *User) error

func (*Store) UpsertIndexedModpack

func (s *Store) UpsertIndexedModpack(ctx context.Context, modpack *IndexedModpack) error

Indexed Modpack operations

func (*Store) UpsertIndexedModpackFile

func (s *Store) UpsertIndexedModpackFile(ctx context.Context, file *IndexedModpackFile) error

Indexed Modpack File operations

func (*Store) UpsertModuleTemplate

func (s *Store) UpsertModuleTemplate(ctx context.Context, template *ModuleTemplate) error

UpsertModuleTemplate creates or updates a module template by ID

func (*Store) UpsertSubuser

func (s *Store) UpsertSubuser(ctx context.Context, serverID, userID string, permissions []string) error

UpsertSubuser grants (or replaces) scoped permissions for a user on a server. Permissions are "resource.action" strings, e.g. "servers.start".

type SystemSetting

type SystemSetting struct {
	Key   string `gorm:"primaryKey"`
	Value string `gorm:"not null"`
}

SystemSetting stores key-value pairs for internal system configuration.

type TaskExecution

type TaskExecution struct {
	ID        string          `json:"id" gorm:"primaryKey"`
	TaskID    string          `json:"task_id" gorm:"not null;index;column:task_id"`
	ServerID  string          `json:"server_id" gorm:"not null;index;column:server_id"`
	Status    ExecutionStatus `json:"status" gorm:"not null"`
	StartedAt time.Time       `json:"started_at" gorm:"not null;column:started_at"`
	EndedAt   *time.Time      `json:"ended_at" gorm:"column:ended_at"`
	Duration  int64           `json:"duration" gorm:"default:0"`                   // Duration in milliseconds
	Output    string          `json:"output" gorm:"type:text"`                     // Output or result
	Error     string          `json:"error" gorm:"type:text"`                      // Error message if failed
	RetryNum  int             `json:"retry_num" gorm:"default:0;column:retry_num"` // Which retry attempt (0 = first try)
	Trigger   string          `json:"trigger" gorm:"default:scheduled"`            // "scheduled", "manual", "startup"

	Task   *ScheduledTask `json:"-" gorm:"foreignKey:TaskID;constraint:OnDelete:CASCADE"`
	Server *Server        `json:"-" gorm:"foreignKey:ServerID;constraint:OnDelete:CASCADE"`
}

TaskExecution represents a single execution of a scheduled task

type TaskStatus

type TaskStatus string

TaskStatus defines the status of a scheduled task

const (
	TaskStatusEnabled  TaskStatus = "enabled"  // Task is active and will run
	TaskStatusDisabled TaskStatus = "disabled" // Task exists but won't run
	TaskStatusPaused   TaskStatus = "paused"   // Temporarily paused
)

type TaskType

type TaskType string

TaskType defines the type of scheduled task

const (
	TaskTypeCommand       TaskType = "command"        // Execute an RCON command
	TaskTypeBackup        TaskType = "backup"         // Create a backup
	TaskTypeRestart       TaskType = "restart"        // Restart the server
	TaskTypeStart         TaskType = "start"          // Start the server
	TaskTypeStop          TaskType = "stop"           // Stop the server
	TaskTypeScript        TaskType = "script"         // Run a custom script
	TaskTypeWebhook       TaskType = "webhook"        // Send an HTTP webhook
	TaskTypeModpackUpdate TaskType = "modpack_update" // Periodically fetch and update modpack from Git/source
	TaskTypeChunkyPregen  TaskType = "chunky_pregen"  // Automated background Chunky radius pre-generation task runner
)

type User

type User struct {
	ID           string     `json:"id" gorm:"primaryKey"`
	Username     string     `json:"username" gorm:"not null;uniqueIndex:idx_user_provider"`
	Email        *string    `json:"email" gorm:"index"`
	PasswordHash string     `json:"-" gorm:"column:password_hash"`
	AuthProvider string     `json:"auth_provider" gorm:"not null;default:'local';uniqueIndex:idx_user_provider"`
	OIDCSubject  string     `json:"oidc_subject" gorm:"column:oidc_subject;uniqueIndex:idx_oidc_identity,where:oidc_subject != ''"`
	OIDCIssuer   string     `json:"oidc_issuer" gorm:"column:oidc_issuer;uniqueIndex:idx_oidc_identity,where:oidc_subject != ''"`
	IsActive     bool       `json:"is_active" gorm:"not null;default:true"`
	LastLogin    *time.Time `json:"last_login" gorm:"column:last_login"`
	CreatedAt    time.Time  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt    time.Time  `json:"updated_at" gorm:"autoUpdateTime"`
}

User represents a user account

type UserRole

type UserRole struct {
	ID        string    `json:"id" gorm:"primaryKey"`
	UserID    string    `json:"user_id" gorm:"not null;index;column:user_id"`
	RoleName  string    `json:"role_name" gorm:"not null;index;column:role_name"`
	Source    string    `json:"source" gorm:"not null;default:'local'"`
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
}

UserRole links users to roles

Jump to

Keyboard shortcuts

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