store

package
v1.20.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: AGPL-3.0 Imports: 24 Imported by: 0

Documentation

Overview

Package store persists the Controller's state in PostgreSQL: desired state, observed state and history. Schema changes are goose migrations embedded in the binary and applied automatically on startup.

Index

Constants

View Source
const WorkflowConditionID = "workflow"

WorkflowConditionID is the Controller's condition on a server whose restore or clone failed.

Variables

View Source
var (
	// ErrNotFound is returned when a record, or a record it refers to, does
	// not exist.
	ErrNotFound = errors.New("not found")
	// ErrConflict is returned when a change clashes with existing data: a
	// duplicate name, or state that changed since the caller read it.
	ErrConflict = errors.New("conflict")
	// ErrCatalogNotNewer is returned when a catalog snapshot is not newer
	// than the stored one. It is not an ErrConflict, so a duplicate key in
	// a snapshot is never mistaken for it.
	ErrCatalogNotNewer = errors.New("the catalog snapshot is not newer than the stored one")
)
View Source
var ErrInUse = errors.New("in use")

ErrInUse is returned for deleting a destination that backups or schedules still use.

Functions

func Migrate

func Migrate(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) error

Migrate applies every pending migration. Concurrent Controllers serialise on a PostgreSQL advisory lock, so only one applies them.

Types

type AssignmentFilter added in v1.4.0

type AssignmentFilter struct {
	UserID *uuid.UUID
	TeamID *uuid.UUID
	RoleID *uuid.UUID
}

AssignmentFilter narrows ListRoleAssignments; nil fields match all.

type AuditFilter

type AuditFilter struct {
	ActorUserID *uuid.UUID
	TargetKind  string
	TargetID    string
	Since       *time.Time
	// Until keeps only events before this time.
	Until *time.Time
	// Action is an area ("server", every "server.…" action) or one action.
	Action  string
	Outcome domain.Outcome
	// BeforeID continues a listing: only events older than this ID.
	BeforeID int64
	// Limit defaults to 100 and is capped at 1000.
	Limit int
}

AuditFilter narrows ListAuditEvents. Zero fields match everything.

type BackupCursor added in v1.18.0

type BackupCursor struct {
	StartedAt time.Time
	ID        uuid.UUID
}

BackupCursor continues a listing of backups after the last one seen.

type CatalogBuild added in v1.13.0

type CatalogBuild struct {
	Template    string
	Version     string
	Build       string
	Channel     string
	URL         string
	Checksum    format.Checksum
	Size        int64
	JavaVersion int
}

CatalogBuild is one server software build from the catalog.

type CatalogSnapshot added in v1.13.0

type CatalogSnapshot struct {
	Sequence    int64
	GeneratedAt time.Time
	SyncedAt    time.Time
	SourceURL   string
}

CatalogSnapshot describes the stored catalog snapshot.

type DeniedPlugin added in v1.14.0

type DeniedPlugin struct {
	ServerID uuid.UUID
	PluginID string
	Name     string
	Version  string
	Reason   string
	Link     string
}

DeniedPlugin is an installed catalog plugin version the denylist names.

type IssuedCert added in v1.6.0

type IssuedCert struct {
	Serial      string
	Fingerprint string
	NotBefore   time.Time
	NotAfter    time.Time
}

IssuedCert is a certificate to record, as produced by the CA.

type Member added in v1.19.0

type Member struct {
	ServerID uuid.UUID
	Name     string
	NodeID   uuid.UUID
	HostPort int
	// NodeAddress is where other Nodes reach the member's Node: as set by
	// an administrator, or else as observed.
	NodeAddress string
}

Member is a network member as the proxy reaches it.

type NewAPIToken added in v1.3.0

type NewAPIToken struct {
	UserID        uuid.UUID
	Name          string
	TokenHash     []byte
	DisplayPrefix string
	// Permissions restricts the token; nil means all of the user's.
	Permissions []domain.Permission
	ExpiresAt   *time.Time
}

NewAPIToken is the input for CreateAPIToken.

type NewRestore added in v1.18.0

type NewRestore struct {
	ServerID uuid.UUID
	// Kind is WorkflowRestore (from BackupID) or WorkflowClone (from
	// SourceServerID, of Parts).
	Kind           domain.WorkflowKind
	BackupID       *uuid.UUID
	SourceServerID *uuid.UUID
	Parts          []domain.DataPart
	// SafetyDestinationID, when set, backs the server up there first.
	SafetyDestinationID *uuid.UUID
	CreatedBy           *uuid.UUID
}

NewRestore starts a restore in place or a clone into a server.

type NewServer

type NewServer struct {
	Name   string
	TeamID uuid.UUID
	// NodeID is nil when placement will choose the Node.
	NodeID        *uuid.UUID
	DesiredState  domain.DesiredServerState
	Software      domain.Software
	Resources     domain.Resources
	RestartPolicy domain.RestartPolicy
	Ports         []domain.Port
	// EULAAcceptedBy is the operator who accepted the Minecraft EULA for
	// this server at creation, or nil if it was not accepted.
	EULAAcceptedBy *uuid.UUID
	CreatedBy      *uuid.UUID
	// Kind is MINECRAFT_SERVER when empty.
	Kind domain.WorkloadKind
	// InNetwork makes the server a network member.
	InNetwork bool
	// InitialProperties are server.properties values for its first start.
	InitialProperties map[string]string
}

NewServer is the input for CreateServer.

type NewUser

type NewUser struct {
	Username    string
	Email       string
	DisplayName string
	GlobalAdmin bool
}

NewUser is the input for CreateUser. Passwords are set separately once authentication exists.

type NodeFacts added in v1.7.0

type NodeFacts struct {
	AgentVersion   string
	Hostname       string
	OS             string
	Arch           string
	RuntimeName    string
	RuntimeVersion string
	Allocatable    domain.ResourceAmounts
}

NodeFacts is what an Agent reports about its machine when its session opens.

type Page added in v1.4.0

type Page struct {
	After *uuid.UUID
	Limit int
}

Page selects part of a list ordered by ID: entries after After (nil for the first page), at most Limit of them.

type PluginChange added in v1.14.0

type PluginChange struct {
	Put    []domain.ServerPlugin
	Remove *uuid.UUID
	// Event names the history event recorded with it.
	Event string
}

PluginChange is one change to a server's plugins: plugins to add or replace (by plugin ID), or one installation to remove.

type PluginFilter added in v1.13.0

type PluginFilter struct {
	Search      string
	Platform    string
	GameVersion string
	// After continues a listing after this plugin (downloads, then ID).
	AfterDownloads *int64
	AfterID        string
	Limit          int
}

PluginFilter narrows a catalog plugin search.

type ProvisioningServer added in v1.11.0

type ProvisioningServer struct {
	ID           uuid.UUID
	CreatedAt    time.Time
	HasArtifact  bool
	DesiredState domain.DesiredServerState
	Phase        domain.ServerPhase
	// SoftwareChangeStartedAt is set while an UPDATING server waits for
	// its new software.
	SoftwareChangeStartedAt *time.Time
}

ProvisioningServer is a server the provisioning workflow handles.

type Release added in v1.18.0

type Release struct {
	ServerID uuid.UUID
	NodeID   uuid.UUID
	// Remove asks the Node to delete the server's container and volume;
	// until then it keeps the server stopped, with its reservation.
	Remove bool
}

Release is a Node holding a server that is not assigned to it.

type RoleAssignment

type RoleAssignment struct {
	RoleID    uuid.UUID
	UserID    *uuid.UUID
	TeamID    *uuid.UUID
	Scope     domain.Scope
	CreatedBy *uuid.UUID
}

RoleAssignment gives a role to exactly one of UserID or TeamID, at Scope.

type ServerFilter added in v1.5.0

type ServerFilter struct {
	Visible domain.Visibility
	Page    Page
}

ServerFilter selects servers for ListServers.

type Store

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

Store reads and writes the Controller's state.

func New

func New(pool *pgxpool.Pool) *Store

New returns a Store backed by pool.

func (*Store) APITokenByHash added in v1.3.0

func (s *Store) APITokenByHash(ctx context.Context, tokenHash []byte) (domain.APIToken, error)

APITokenByHash returns the token for a hash, whether or not it is active.

func (*Store) AcknowledgeCondition

func (s *Store) AcknowledgeCondition(ctx context.Context, id uuid.UUID, conditionID string, by *uuid.UUID) (int64, error)

AcknowledgeCondition records that an administrator acknowledged an active condition on a server, and returns the new generation: the acknowledgement is part of the desired spec the Agent receives.

func (*Store) AddArtifact added in v1.11.0

func (s *Store) AddArtifact(ctx context.Context, a domain.Artifact) (domain.Artifact, error)

AddArtifact records an artifact whose file is in place. An artifact with the same SHA-256 is the same file: the existing record is returned.

func (*Store) AddPluginArtifact added in v1.14.0

func (s *Store) AddPluginArtifact(ctx context.Context, a domain.PluginArtifact) (domain.PluginArtifact, error)

AddPluginArtifact records a plugin jar whose file is in place. A jar with the same SHA-256 is the same file: the existing record is returned.

func (*Store) AddRelease added in v1.18.0

func (s *Store) AddRelease(ctx context.Context, r Release) error

AddRelease records that a Node holds a server it is no longer assigned.

func (*Store) AddTeamMember

func (s *Store) AddTeamMember(ctx context.Context, teamID, userID uuid.UUID) error

AddTeamMember adds a user to a team. Adding an existing member is a no-op.

func (*Store) AppendAgentEvents

func (s *Store) AppendAgentEvents(ctx context.Context, nodeID uuid.UUID, events []domain.AgentEvent) (inserted, throughSeq int64, err error)

AppendAgentEvents stores events an Agent replayed. Events already stored (same Node and sequence number) are skipped, so replays are idempotent. It returns how many events were new and the highest sequence number in the batch, which the Controller acknowledges back to the Agent.

func (*Store) AppendAuditEvent

func (s *Store) AppendAuditEvent(ctx context.Context, e domain.AuditEvent) (domain.AuditEvent, error)

AppendAuditEvent records an audited action and returns it as stored.

func (*Store) ApplyServerStatus

func (s *Store) ApplyServerStatus(ctx context.Context, id uuid.UUID, st domain.ServerStatus) error

ApplyServerStatus records an Agent report for a server: its observed state and the full set of Agent conditions. Controller conditions are kept. Runtime history comes from the Agent's own events, so no event is written here.

func (*Store) ArtifactAssignedToNode added in v1.11.0

func (s *Store) ArtifactAssignedToNode(ctx context.Context, artifactID, nodeID uuid.UUID) (bool, error)

ArtifactAssignedToNode reports whether a server on the Node runs the artifact, which is what lets the Node fetch it.

func (*Store) ArtifactVersions added in v1.11.0

func (s *Store) ArtifactVersions(ctx context.Context, template string) ([]string, error)

ArtifactVersions returns the versions of a template that have a cached artifact.

func (*Store) AssignRole

func (s *Store) AssignRole(ctx context.Context, a RoleAssignment) (uuid.UUID, error)

AssignRole records a role assignment and returns its ID.

func (*Store) BumpNetworkMembers added in v1.19.0

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

BumpNetworkMembers raises every member's generation: whether they take players from the proxy changes when it comes or goes.

func (*Store) BumpProxy added in v1.19.0

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

BumpProxy raises the proxy's generation, so its Agent applies a changed routing table. Without a proxy it does nothing.

func (*Store) CatalogSoftwareBuild added in v1.13.0

func (s *Store) CatalogSoftwareBuild(ctx context.Context, template, version, build string) (CatalogBuild, error)

CatalogSoftwareBuild returns a build from the stored snapshot: the given one, or the newest stable one when build is empty.

func (*Store) CatalogSoftwareVersions added in v1.13.0

func (s *Store) CatalogSoftwareVersions(ctx context.Context, template string) ([]string, error)

CatalogSoftwareVersions lists a template's versions in the stored snapshot, newest first.

func (*Store) ChangeResources added in v1.12.0

func (s *Store) ChangeResources(ctx context.Context, id uuid.UUID, r domain.Resources) (int64, error)

ChangeResources changes a READY server's CPU and memory reservation, if the new one fits on its Node with its current reservation excluded. The Node is locked as for placement, so concurrent changes and placements never overcommit it.

func (*Store) ChangeServerPlugins added in v1.14.0

func (s *Store) ChangeServerPlugins(ctx context.Context, serverID uuid.UUID, c PluginChange) (int64, []domain.ServerPlugin, error)

ChangeServerPlugins applies a change to a READY server's plugins as a new generation of its spec. Within the transaction it checks that no plugin is left without a dependency it requires: removing a required plugin is ErrPluginRequired, and a dependency removed concurrently is ErrConflict. It returns the new generation and the server's plugins.

func (*Store) ClearServerCondition added in v1.14.0

func (s *Store) ClearServerCondition(ctx context.Context, id uuid.UUID, source domain.ConditionSource, conditionID string) error

ClearServerCondition removes one condition from a server, by its ID.

func (*Store) CountActiveGlobalAdmins added in v1.3.0

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

CountActiveGlobalAdmins returns how many enabled global administrators exist, so the last one cannot be removed.

func (*Store) CreateAPIToken added in v1.3.0

func (s *Store) CreateAPIToken(ctx context.Context, t NewAPIToken) (domain.APIToken, error)

CreateAPIToken records a new API token. Names are unique per user among tokens that are not revoked.

func (*Store) CreateDestination added in v1.18.0

func (s *Store) CreateDestination(ctx context.Context, d domain.Destination) (domain.Destination, error)

CreateDestination adds a backup destination with its keys.

func (*Store) CreateNetwork added in v1.19.0

func (s *Store) CreateNetwork(ctx context.Context, n domain.Network) (domain.Network, error)

CreateNetwork sets the network up, with a new forwarding secret. It fails with ErrConflict when the network already exists.

func (*Store) CreateNode

func (s *Store) CreateNode(ctx context.Context, name string, createdBy *uuid.UUID) (domain.Node, error)

CreateNode adds a Node, ENABLED and AWAITING_ENROLLMENT.

func (*Store) CreatePasswordReset added in v1.3.0

func (s *Store) CreatePasswordReset(ctx context.Context, userID uuid.UUID, tokenHash []byte, now time.Time, createdBy *uuid.UUID) error

CreatePasswordReset records a one-time reset link for a user, valid until now plus domain.PasswordResetLifetime.

func (*Store) CreateRole

func (s *Store) CreateRole(ctx context.Context, name, description string, perms []domain.Permission) (uuid.UUID, error)

CreateRole adds a custom role with the given permissions.

func (*Store) CreateSchedule added in v1.18.0

func (s *Store) CreateSchedule(ctx context.Context, sc domain.Schedule) (domain.Schedule, error)

CreateSchedule adds a schedule. The server's spec changes with it, so its generation is raised in the same transaction.

func (*Store) CreateServer

func (s *Store) CreateServer(ctx context.Context, n NewServer) (domain.Server, error)

CreateServer adds a server in phase PROVISIONING at generation 1.

func (*Store) CreateSession added in v1.3.0

func (s *Store) CreateSession(ctx context.Context, userID uuid.UUID, tokenHash []byte, now time.Time) (domain.Session, error)

CreateSession records a new session for tokenHash, starting at now.

func (*Store) CreateTeam

func (s *Store) CreateTeam(ctx context.Context, name string) (domain.Team, error)

CreateTeam adds a team. Names are unique, ignoring case.

func (*Store) CreateUser

func (s *Store) CreateUser(ctx context.Context, u NewUser) (domain.User, error)

CreateUser adds a user. Usernames and emails are unique, ignoring case.

func (*Store) CreateWorkflow added in v1.18.0

func (s *Store) CreateWorkflow(ctx context.Context, w domain.Workflow) (domain.Workflow, error)

CreateWorkflow records a workflow for a server; a server has at most one running (ErrConflict otherwise).

func (*Store) DeleteBackup added in v1.18.0

func (s *Store) DeleteBackup(ctx context.Context, id uuid.UUID) error

DeleteBackup removes a backup record.

func (*Store) DeleteDestination added in v1.18.0

func (s *Store) DeleteDestination(ctx context.Context, id uuid.UUID) error

DeleteDestination removes a destination no backup or schedule uses.

func (*Store) DeleteExpiredSessions added in v1.3.0

func (s *Store) DeleteExpiredSessions(ctx context.Context, now time.Time) (int64, error)

DeleteExpiredSessions removes sessions that are no longer active at now.

func (*Store) DeleteNode added in v1.5.0

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

DeleteNode removes a Node no server is assigned to.

func (*Store) DeleteRelease added in v1.18.0

func (s *Store) DeleteRelease(ctx context.Context, serverID, nodeID uuid.UUID) (bool, error)

DeleteRelease forgets a release once the Node removed the server, or when the server comes back to the Node. It reports whether there was one.

func (*Store) DeleteRole added in v1.4.0

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

DeleteRole removes a custom role and every assignment of it; built-in roles fail with domain.ErrBuiltinRole.

func (*Store) DeleteRoleAssignment added in v1.4.0

func (s *Store) DeleteRoleAssignment(ctx context.Context, id uuid.UUID) error

DeleteRoleAssignment removes an assignment.

func (*Store) DeleteSchedule added in v1.18.0

func (s *Store) DeleteSchedule(ctx context.Context, serverID, id uuid.UUID) error

DeleteSchedule removes a schedule and raises its server's generation.

func (*Store) DeleteServerRecord added in v1.8.0

func (s *Store) DeleteServerRecord(ctx context.Context, id uuid.UUID) error

DeleteServerRecord removes a server whose deletion the Agent confirmed. Its history stays. Only a server whose desired state is DELETED is removed; anything else is left alone and reported as a conflict.

func (*Store) DeleteSession added in v1.3.0

func (s *Store) DeleteSession(ctx context.Context, userID, id uuid.UUID) error

DeleteSession ends one of a user's sessions. Another user's session is reported as not found.

func (*Store) DeleteTeam added in v1.4.0

func (s *Store) DeleteTeam(ctx context.Context, id uuid.UUID) error

DeleteTeam removes a team that owns no servers. Its memberships and the role assignments held by or scoped to it go with it.

func (*Store) DeleteUser added in v1.4.0

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

DeleteUser removes a user and, through cascades, their sessions, tokens, memberships and role assignments. History keeps their ID.

func (*Store) DeleteUserSessions added in v1.3.0

func (s *Store) DeleteUserSessions(ctx context.Context, userID uuid.UUID, keep *uuid.UUID) error

DeleteUserSessions ends every session of a user except keep, if set.

func (*Store) DeniedPlugins added in v1.14.0

func (s *Store) DeniedPlugins(ctx context.Context) ([]DeniedPlugin, error)

DeniedPlugins returns every installed plugin version the stored denylist names, by server.

func (*Store) Enroll added in v1.6.0

func (s *Store) Enroll(ctx context.Context, tokenID uuid.UUID, secretHash []byte, now time.Time,
	sign func(nodeID uuid.UUID) (IssuedCert, error)) (uuid.UUID, error)

Enroll redeems an enrollment token: it checks the secret against the stored hash in constant time, has sign issue the Node's certificate, records it and deletes the token, all in one transaction, so a token works once and every issued certificate is recorded. Every refusal is domain.ErrInvalidEnrollmentToken.

func (*Store) FailStaleBackups added in v1.18.0

func (s *Store) FailStaleBackups(ctx context.Context, before time.Time, reason string) ([]domain.Backup, error)

FailStaleBackups marks backups still running from before a time as failed, and returns them.

func (*Store) FindArtifact added in v1.11.0

func (s *Store) FindArtifact(ctx context.Context, template, version, build string) (domain.Artifact, error)

FindArtifact returns the newest artifact for a template and version, and build unless it is empty.

func (*Store) FindArtifactBySHA256 added in v1.14.0

func (s *Store) FindArtifactBySHA256(ctx context.Context, sum []byte) (domain.Artifact, error)

FindArtifactBySHA256 returns a software artifact by its SHA-256.

func (*Store) FindCatalogPluginArtifact added in v1.14.0

func (s *Store) FindCatalogPluginArtifact(ctx context.Context, pluginID, versionID string) (domain.PluginArtifact, error)

FindCatalogPluginArtifact returns the cached jar of a catalog plugin version.

func (*Store) FinishBackup added in v1.18.0

func (s *Store) FinishBackup(ctx context.Context, b domain.Backup) (domain.Backup, bool, error)

FinishBackup records an Agent's report of a backup it took: one the Controller asked for, or a scheduled one, recorded here for the first time with the server's plugins as they are now. A report about a backup that is no longer running changes nothing; ok is false then.

func (*Store) FinishMigration added in v1.18.0

func (s *Store) FinishMigration(ctx context.Context, w domain.Workflow, failure string, gamePorts domain.PortRange) error

FinishMigration ends a migration. On success the old Node is told to remove its copy; on failure the server goes back to the old Node (its reservation was held there) and the new Node removes what it received. Either way the server is READY again, and runs if it should.

func (*Store) FinishRestore added in v1.18.0

func (s *Store) FinishRestore(ctx context.Context, w domain.Workflow, failure string) error

FinishRestore ends a restore, restore as new or clone. On success the server is READY (and running again if it should run, or if it was restored as new to start afterwards); a clone copies schedules when asked. On failure it is FAILED and stopped, with a condition saying why.

func (*Store) FinishSoftwareChange added in v1.14.0

func (s *Store) FinishSoftwareChange(ctx context.Context, id uuid.UUID, a domain.Artifact) (int64, error)

FinishSoftwareChange records the new software of an UPDATING server as a new generation of its spec, and makes it READY again.

func (*Store) FinishWorkflow added in v1.18.0

func (s *Store) FinishWorkflow(ctx context.Context, id uuid.UUID, state domain.WorkflowState, reason string) error

FinishWorkflow ends a running workflow.

func (*Store) ForgetBackupObject added in v1.18.0

func (s *Store) ForgetBackupObject(ctx context.Context, destinationID uuid.UUID, objectKey string) error

ForgetBackupObject removes the record of a stored backup an Agent deleted under retention. Unknown objects are ignored.

func (*Store) ForwardingSecret added in v1.19.0

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

ForwardingSecret returns the secret Velocity's modern forwarding uses, or "" before setup. It never leaves the Controller except to Agents.

func (*Store) GetArtifact added in v1.11.0

func (s *Store) GetArtifact(ctx context.Context, id uuid.UUID) (domain.Artifact, error)

GetArtifact returns an artifact by ID.

func (*Store) GetBackup added in v1.18.0

func (s *Store) GetBackup(ctx context.Context, id uuid.UUID) (domain.Backup, error)

GetBackup returns a backup record.

func (*Store) GetCatalogPlugin added in v1.13.0

func (s *Store) GetCatalogPlugin(ctx context.Context, id string) (format.Plugin, []format.Denial, error)

GetCatalogPlugin returns a catalog plugin with its versions and the denylist entries about it.

func (*Store) GetCatalogSnapshot added in v1.13.0

func (s *Store) GetCatalogSnapshot(ctx context.Context) (CatalogSnapshot, error)

GetCatalogSnapshot returns the stored snapshot's description, or ErrNotFound before the first sync.

func (*Store) GetDestination added in v1.18.0

func (s *Store) GetDestination(ctx context.Context, id uuid.UUID) (domain.Destination, error)

GetDestination returns a destination with its secrets.

func (*Store) GetNetwork added in v1.19.0

func (s *Store) GetNetwork(ctx context.Context) (domain.Network, error)

GetNetwork returns the network profile, or ErrNotFound before setup.

func (*Store) GetNode

func (s *Store) GetNode(ctx context.Context, id uuid.UUID) (domain.Node, error)

GetNode returns a Node with its observed status and conditions.

func (*Store) GetPluginArtifact added in v1.14.0

func (s *Store) GetPluginArtifact(ctx context.Context, id uuid.UUID) (domain.PluginArtifact, error)

GetPluginArtifact returns a plugin jar by ID.

func (*Store) GetPluginArtifactBySHA256 added in v1.14.0

func (s *Store) GetPluginArtifactBySHA256(ctx context.Context, sum []byte) (domain.PluginArtifact, error)

GetPluginArtifactBySHA256 returns a plugin jar by its SHA-256.

func (*Store) GetRole added in v1.4.0

func (s *Store) GetRole(ctx context.Context, id uuid.UUID) (domain.Role, error)

GetRole returns a role with its permissions.

func (*Store) GetSchedule added in v1.18.0

func (s *Store) GetSchedule(ctx context.Context, serverID, id uuid.UUID) (domain.Schedule, error)

GetSchedule returns one of a server's schedules.

func (*Store) GetServer

func (s *Store) GetServer(ctx context.Context, id uuid.UUID) (domain.Server, error)

GetServer returns a server's desired spec.

func (*Store) GetServerPlugin added in v1.14.0

func (s *Store) GetServerPlugin(ctx context.Context, serverID, id uuid.UUID) (domain.ServerPlugin, error)

GetServerPlugin returns one of a server's plugins by installation ID.

func (*Store) GetServerStatus

func (s *Store) GetServerStatus(ctx context.Context, id uuid.UUID) (domain.ServerStatus, error)

GetServerStatus returns a server's observed state and conditions.

func (*Store) GetTeam added in v1.4.0

func (s *Store) GetTeam(ctx context.Context, id uuid.UUID) (domain.Team, error)

GetTeam returns a team.

func (*Store) GetUser

func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (domain.User, error)

GetUser returns the user with the given ID.

func (*Store) GetWorkflow added in v1.18.0

func (s *Store) GetWorkflow(ctx context.Context, id uuid.UUID) (domain.Workflow, error)

GetWorkflow returns a workflow.

func (*Store) GrantsForUser

func (s *Store) GrantsForUser(ctx context.Context, userID uuid.UUID) ([]domain.Grant, error)

GrantsForUser returns every grant in effect for a user, held directly or through team membership, ready for domain.Authorize.

func (*Store) HasUsers added in v1.19.0

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

HasUsers reports whether any user exists: until one does, the Controller waits for first-run setup.

func (*Store) InTx

func (s *Store) InTx(ctx context.Context, fn func(tx *Store) error) error

InTx runs fn in a transaction, committing if it returns nil. Store methods called on tx join the transaction (nested calls use savepoints), so callers can make a change and record its audit event atomically.

func (*Store) IssueEnrollmentToken added in v1.6.0

func (s *Store) IssueEnrollmentToken(ctx context.Context, nodeID uuid.UUID, secretHash []byte, expiresAt time.Time, createdBy *uuid.UUID) (uuid.UUID, error)

IssueEnrollmentToken records a token for a Node that is still awaiting enrollment, replacing any earlier one, and returns the token's ID.

func (*Store) ListAPITokens added in v1.3.0

func (s *Store) ListAPITokens(ctx context.Context, userID uuid.UUID) ([]domain.APIToken, error)

ListAPITokens returns a user's tokens that are not revoked.

func (*Store) ListArtifacts added in v1.11.0

func (s *Store) ListArtifacts(ctx context.Context) ([]domain.Artifact, error)

ListArtifacts returns every cached artifact, newest first.

func (*Store) ListAuditEvents

func (s *Store) ListAuditEvents(ctx context.Context, f AuditFilter) ([]domain.AuditEvent, error)

ListAuditEvents returns audit events newest first.

func (*Store) ListDestinations added in v1.18.0

func (s *Store) ListDestinations(ctx context.Context) ([]domain.Destination, error)

ListDestinations returns every destination, with secrets, by name.

func (*Store) ListNodes added in v1.5.0

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

ListNodes returns Nodes in creation order, with their observed status but without conditions.

func (*Store) ListPermissions added in v1.4.0

func (s *Store) ListPermissions(ctx context.Context) ([]domain.PermissionInfo, error)

ListPermissions returns the permission catalog.

func (*Store) ListRoleAssignments added in v1.4.0

func (s *Store) ListRoleAssignments(ctx context.Context, f AssignmentFilter) ([]domain.RoleAssignment, error)

ListRoleAssignments returns role assignments, oldest first.

func (*Store) ListRoles added in v1.4.0

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

ListRoles returns every role, built-in roles first.

func (*Store) ListServerBackups added in v1.18.0

func (s *Store) ListServerBackups(ctx context.Context, serverID uuid.UUID, after *BackupCursor, limit int) ([]domain.Backup, error)

ListServerBackups returns a server's backups, newest first.

func (*Store) ListServerEvents added in v1.5.0

func (s *Store) ListServerEvents(ctx context.Context, serverID uuid.UUID, beforeID int64, limit int) ([]domain.Event, error)

ListServerEvents returns a server's history, newest first: events older than beforeID when it is positive, at most limit of them.

func (*Store) ListServerPlugins added in v1.14.0

func (s *Store) ListServerPlugins(ctx context.Context, serverID uuid.UUID) ([]domain.ServerPlugin, error)

ListServerPlugins returns a server's plugins: those installed directly first, then dependencies, by name.

func (*Store) ListServerSchedules added in v1.18.0

func (s *Store) ListServerSchedules(ctx context.Context, serverID uuid.UUID) ([]domain.Schedule, error)

ListServerSchedules returns a server's schedules, oldest first.

func (*Store) ListServers added in v1.5.0

func (s *Store) ListServers(ctx context.Context, f ServerFilter) ([]domain.ServerSummary, error)

ListServers returns the visible servers in creation order.

func (*Store) ListSessions added in v1.3.0

func (s *Store) ListSessions(ctx context.Context, userID uuid.UUID, now time.Time) ([]domain.Session, error)

ListSessions returns a user's sessions that are still active at now, newest first.

func (*Store) ListTeamMembers added in v1.4.0

func (s *Store) ListTeamMembers(ctx context.Context, teamID uuid.UUID) ([]domain.User, error)

ListTeamMembers returns a team's members by username.

func (*Store) ListTeams added in v1.4.0

func (s *Store) ListTeams(ctx context.Context, p Page) ([]domain.Team, error)

ListTeams returns teams in creation order.

func (*Store) ListUsers added in v1.4.0

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

ListUsers returns users in creation order.

func (*Store) MarkStaleNodesUnreachable added in v1.7.0

func (s *Store) MarkStaleNodesUnreachable(ctx context.Context, cutoff time.Time) ([]uuid.UUID, error)

MarkStaleNodesUnreachable marks every connected Node whose last heartbeat is older than cutoff UNREACHABLE and returns their IDs. It reads only the database, so it works after a Controller restart too.

func (s *Store) NetworkLogo(ctx context.Context) ([]byte, time.Time, error)

NetworkLogo returns the logo (PNG) and when the profile last changed, or ErrNotFound without one.

func (*Store) NetworkMembers added in v1.19.0

func (s *Store) NetworkMembers(ctx context.Context) ([]Member, error)

NetworkMembers lists the members the proxy can route to, by name.

func (*Store) NodeCertificate added in v1.6.0

func (s *Store) NodeCertificate(ctx context.Context, serial string) (domain.NodeCertificate, error)

NodeCertificate returns a certificate the CA issued, by serial.

func (*Store) NodeConnectionState added in v1.5.0

func (s *Store) NodeConnectionState(ctx context.Context, id uuid.UUID) (domain.NodeConnectionState, error)

NodeConnectionState returns a Node's observed connection state.

func (*Store) NodeReleases added in v1.18.0

func (s *Store) NodeReleases(ctx context.Context, nodeID uuid.UUID) ([]Release, error)

NodeReleases returns the servers a Node holds without being assigned them.

func (*Store) PlaceServer added in v1.9.0

func (s *Store) PlaceServer(ctx context.Context, n NewServer, gamePorts domain.PortRange) (domain.Server, error)

PlaceServer creates a server on a Node with room for it, reserving its CPU and memory and its host ports, in one transaction. With n.NodeID set that Node is checked (ENABLED, enough unreserved capacity); otherwise domain.Place chooses among the Nodes that accept placements. Without a game port in n.Ports, the first free TCP port in gamePorts is assigned. The Node rows stay locked until the transaction ends, so concurrent placements never overcommit a Node or share a port.

func (*Store) PluginArtifactAssignedToNode added in v1.14.0

func (s *Store) PluginArtifactAssignedToNode(ctx context.Context, artifactID, nodeID uuid.UUID) (bool, error)

PluginArtifactAssignedToNode reports whether a server on the Node has the plugin jar, which is what lets the Node fetch it.

func (*Store) ProvisioningServers added in v1.11.0

func (s *Store) ProvisioningServers(ctx context.Context) ([]ProvisioningServer, error)

ProvisioningServers lists servers in PROVISIONING, and servers being deleted that never got software, oldest first.

func (*Store) ProxyServer added in v1.19.0

func (s *Store) ProxyServer(ctx context.Context) (domain.Server, error)

ProxyServer returns the network's proxy, or ErrNotFound without one.

func (*Store) PurgeExpiredEnrollmentTokens added in v1.6.0

func (s *Store) PurgeExpiredEnrollmentTokens(ctx context.Context, now time.Time) (int, error)

PurgeExpiredEnrollmentTokens deletes expired enrollment tokens and returns how many it deleted. Their Nodes stay AWAITING_ENROLLMENT, so an operator can issue a fresh token; each expiry is recorded in the Node's history.

func (*Store) RecordHeartbeat added in v1.7.0

func (s *Store) RecordHeartbeat(ctx context.Context, nodeID uuid.UUID, usage domain.ResourceAmounts, pressure bool, at time.Time) (domain.NodeConnectionState, error)

RecordHeartbeat stores a heartbeat's usage and moves the Node to HEALTHY, or DEGRADED when it reports pressure, following the Node state machine. The state machine has no direct step from AWAITING_ENROLLMENT to DEGRADED, so a first heartbeat under pressure passes through HEALTHY; every step is recorded. It returns the new state.

func (*Store) RecordNodeFacts added in v1.7.0

func (s *Store) RecordNodeFacts(ctx context.Context, nodeID uuid.UUID, f NodeFacts, connectedAt time.Time) error

RecordNodeFacts stores an Agent's facts without touching its connection state or usage.

func (*Store) RecordObservedAddress added in v1.19.0

func (s *Store) RecordObservedAddress(ctx context.Context, id uuid.UUID, address string) (bool, error)

RecordObservedAddress remembers the address a Node's Agent connected from. It reports whether it changed (the proxy's spec then follows).

func (*Store) RecordRotatedCertificate added in v1.8.0

func (s *Store) RecordRotatedCertificate(ctx context.Context, nodeID uuid.UUID, sign func() (IssuedCert, error)) error

RecordRotatedCertificate records a certificate issued to an enrolled Node over its session. sign runs inside the transaction, after the Node is locked and checked, so a revoked Node is never issued one.

func (*Store) RedeemPasswordReset added in v1.3.0

func (s *Store) RedeemPasswordReset(ctx context.Context, tokenHash []byte, now time.Time) (uuid.UUID, error)

RedeemPasswordReset uses up a reset link and returns its user. Unknown, used and expired links all fail with ErrNotFound.

func (*Store) RefreshPluginDenials added in v1.14.0

func (s *Store) RefreshPluginDenials(ctx context.Context, serverID *uuid.UUID, now time.Time) error

RefreshPluginDenials sets the PLUGIN_DENYLISTED condition on every server with an installed plugin version the stored denylist names, and clears it everywhere else. With serverID set, only that server is refreshed.

func (*Store) RemoveReleased added in v1.18.0

func (s *Store) RemoveReleased(ctx context.Context, serverID, nodeID uuid.UUID) error

RemoveReleased asks a Node to remove a server it holds.

func (*Store) RemoveTeamMember

func (s *Store) RemoveTeamMember(ctx context.Context, teamID, userID uuid.UUID) error

RemoveTeamMember removes a user from a team. A user who is not a member is reported as not found.

func (*Store) RenameTeam added in v1.4.0

func (s *Store) RenameTeam(ctx context.Context, id uuid.UUID, name string) (domain.Team, error)

RenameTeam changes a team's name. Names are unique, ignoring case.

func (*Store) ReplaceCatalog added in v1.13.0

func (s *Store) ReplaceCatalog(ctx context.Context, ix format.Index, sourceURL string, syncedAt time.Time,
	sw format.Software, pl format.Plugins, dl format.Denylist) error

ReplaceCatalog stores a verified snapshot in place of the current one, in one transaction. A snapshot not newer than the stored one is refused with ErrCatalogNotNewer, so a replayed old snapshot never replaces a newer one.

func (*Store) ReplaceNodeConditions

func (s *Store) ReplaceNodeConditions(ctx context.Context, id uuid.UUID, source domain.ConditionSource, conds []domain.Condition) error

ReplaceNodeConditions replaces every condition on a Node from source with conds: conditions are reported as a full set, so one missing from conds has cleared. Conditions from the other source are kept.

func (*Store) ReplaceServerConditions added in v1.8.0

func (s *Store) ReplaceServerConditions(ctx context.Context, id uuid.UUID, source domain.ConditionSource, conds []domain.Condition) error

ReplaceServerConditions replaces every condition on a server from source with conds, keeping the other source's.

func (*Store) RequestRestart added in v1.12.0

func (s *Store) RequestRestart(ctx context.Context, id uuid.UUID) (int64, error)

RequestRestart asks for a server to be restarted: a new generation of its spec with a higher restart count. It must be READY and desired RUNNING.

func (*Store) RevertSoftwareChange added in v1.14.0

func (s *Store) RevertSoftwareChange(ctx context.Context, id uuid.UUID, msg string, now time.Time) error

RevertSoftwareChange gives up an UPDATING server's software change: it keeps the software it has, is READY again, and gets a Controller condition saying why.

func (*Store) RevokeAPIToken added in v1.3.0

func (s *Store) RevokeAPIToken(ctx context.Context, userID, id uuid.UUID) error

RevokeAPIToken revokes one of a user's tokens. Another user's token, or one already revoked, is reported as not found.

func (*Store) RevokeUserAPITokens added in v1.3.0

func (s *Store) RevokeUserAPITokens(ctx context.Context, userID uuid.UUID) error

RevokeUserAPITokens revokes every token of a user.

func (*Store) RoleIDByName

func (s *Store) RoleIDByName(ctx context.Context, name string) (uuid.UUID, error)

RoleIDByName returns the ID of the role with the given name, ignoring case.

func (*Store) RunningWorkflow added in v1.18.0

func (s *Store) RunningWorkflow(ctx context.Context, serverID uuid.UUID) (domain.Workflow, error)

RunningWorkflow returns a server's running workflow (ErrNotFound if none).

func (*Store) RunningWorkflows added in v1.18.0

func (s *Store) RunningWorkflows(ctx context.Context) ([]domain.Workflow, error)

RunningWorkflows returns every running workflow, oldest first.

func (*Store) SchedulesForServers added in v1.18.0

func (s *Store) SchedulesForServers(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID][]domain.Schedule, error)

SchedulesForServers returns the schedules of several servers, by server.

func (*Store) SearchCatalogPlugins added in v1.13.0

func (s *Store) SearchCatalogPlugins(ctx context.Context, f PluginFilter) ([]format.Plugin, error)

SearchCatalogPlugins lists catalog plugins, most downloaded first, without their versions.

func (*Store) ServerPluginRefs added in v1.14.0

func (s *Store) ServerPluginRefs(ctx context.Context, serverIDs []uuid.UUID) (map[uuid.UUID][]domain.PluginRef, error)

ServerPluginRefs returns what the specs of these servers carry about their plugins, by server.

func (*Store) ServerReleases added in v1.18.0

func (s *Store) ServerReleases(ctx context.Context, serverID uuid.UUID) ([]Release, error)

ServerReleases returns the Nodes holding a server they are not assigned.

func (*Store) ServersForNode added in v1.8.0

func (s *Store) ServersForNode(ctx context.Context, nodeID uuid.UUID) ([]domain.Server, error)

ServersForNode returns the desired specs of every server assigned to a Node.

func (*Store) SessionByTokenHash added in v1.3.0

func (s *Store) SessionByTokenHash(ctx context.Context, tokenHash []byte) (domain.Session, error)

SessionByTokenHash returns the session for a token hash, active or not.

func (s *Store) SetNetworkLogo(ctx context.Context, png []byte) error

SetNetworkLogo stores a PNG logo, or removes it when png is nil.

func (*Store) SetNodeAddress added in v1.19.0

func (s *Store) SetNodeAddress(ctx context.Context, id uuid.UUID, address string) error

SetNodeAddress sets where other Nodes reach a Node; "" falls back to the address its Agent connects from. The proxy's spec follows.

func (*Store) SetNodeAdminState

func (s *Store) SetNodeAdminState(ctx context.Context, id uuid.UUID, to domain.NodeAdminState) error

SetNodeAdminState changes a Node's admin state following the Node state machine. Setting the current state again is a no-op.

func (*Store) SetPassword added in v1.3.0

func (s *Store) SetPassword(ctx context.Context, userID uuid.UUID, hash string, changeRequired bool) error

SetPassword stores a new password hash. changeRequired forces the user to choose a new password at their next sign-in.

func (*Store) SetServerArtifact added in v1.11.0

func (s *Store) SetServerArtifact(ctx context.Context, serverID uuid.UUID, a domain.Artifact) (int64, error)

SetServerArtifact records the artifact (and resolved build) a server runs, as a new generation of its spec.

func (*Store) SetServerCondition added in v1.14.0

func (s *Store) SetServerCondition(ctx context.Context, id uuid.UUID, source domain.ConditionSource, c domain.Condition) error

SetServerCondition sets one condition on a server, by its ID, leaving the server's other conditions alone. A condition that keeps its reason keeps the time it began.

func (*Store) SetServerDesiredState

func (s *Store) SetServerDesiredState(ctx context.Context, id uuid.UUID, to domain.DesiredServerState) (int64, error)

SetServerDesiredState changes what the user wants a server to be and returns the new generation. It fails with domain.ErrPhaseBusy while another workflow runs. Setting the current desired state again is a no-op.

func (*Store) SetServerInNetwork added in v1.19.0

func (s *Store) SetServerInNetwork(ctx context.Context, id uuid.UUID, in bool) error

SetServerInNetwork makes a server a member or not. Only Paper, Purpur and Folia servers can be members. Leaving takes it out of the lobby.

func (*Store) SetServerPhase

func (s *Store) SetServerPhase(ctx context.Context, id uuid.UUID, from, to domain.ServerPhase) error

SetServerPhase moves a server from phase from to phase to. It fails with ErrConflict if the server is no longer in phase from, so concurrent workflows cannot both claim it.

func (*Store) SetWorkflowStep added in v1.18.0

func (s *Store) SetWorkflowStep(ctx context.Context, id uuid.UUID, step string) error

SetWorkflowStep records how far a running workflow got.

func (*Store) StartBackup added in v1.18.0

func (s *Store) StartBackup(ctx context.Context, b domain.Backup) (domain.Backup, error)

StartBackup records a backup the Controller asked an Agent for, with the server's managed plugins as they are now.

func (*Store) StartMigration added in v1.18.0

func (s *Store) StartMigration(ctx context.Context, serverID, toNode uuid.UUID, gamePorts domain.PortRange, by *uuid.UUID) (domain.Workflow, error)

StartMigration moves a READY server's assignment to another Node: reservation and ports there (the same game port if it is free), a held release on the old Node (which keeps the server stopped and its reservation, so a rollback fits), phase MIGRATING and the workflow.

func (*Store) StartRestore added in v1.18.0

func (s *Store) StartRestore(ctx context.Context, n NewRestore) (domain.Workflow, error)

StartRestore moves a READY (or FAILED) server to RESTORING, which keeps it stopped, records the safety backup it will take and the workflow, and returns the workflow. Its new spec must be pushed after.

func (*Store) StartSoftwareChange added in v1.14.0

func (s *Store) StartSoftwareChange(ctx context.Context, id uuid.UUID, version, build string, now time.Time) error

StartSoftwareChange records a READY server's new software version and build (empty for the newest) and moves it to UPDATING, where the provisioning worker obtains the software. The server keeps running its current software meanwhile.

func (*Store) TeamByName

func (s *Store) TeamByName(ctx context.Context, name string) (domain.Team, error)

TeamByName returns the team with the given name, ignoring case.

func (*Store) TouchAPIToken added in v1.3.0

func (s *Store) TouchAPIToken(ctx context.Context, id uuid.UUID, now time.Time) error

TouchAPIToken records that a token was used at now.

func (*Store) TouchSession added in v1.3.0

func (s *Store) TouchSession(ctx context.Context, id uuid.UUID, now time.Time) error

TouchSession records that a session was used at now.

func (*Store) UpdateDestination added in v1.18.0

func (s *Store) UpdateDestination(ctx context.Context, d domain.Destination) (domain.Destination, error)

UpdateDestination changes a destination's settings. Its kind and keys never change, and an empty secret access key keeps the stored one.

func (*Store) UpdateNetwork added in v1.19.0

func (s *Store) UpdateNetwork(ctx context.Context, n domain.Network) (domain.Network, error)

UpdateNetwork changes the profile. Lobby servers must be members. The proxy's spec follows.

func (*Store) UpdateNodeStatus

func (s *Store) UpdateNodeStatus(ctx context.Context, id uuid.UUID, st domain.NodeStatus) error

UpdateNodeStatus records a Node's observed status. A change of connection state must follow the Node state machine and is written to the history.

func (*Store) UpdateRole added in v1.4.0

func (s *Store) UpdateRole(ctx context.Context, id uuid.UUID, p domain.RolePatch) (domain.Role, error)

UpdateRole changes a custom role; built-in roles fail with domain.ErrBuiltinRole.

func (*Store) UpdateSchedule added in v1.18.0

func (s *Store) UpdateSchedule(ctx context.Context, sc domain.Schedule) (domain.Schedule, error)

UpdateSchedule changes a schedule and raises its server's generation.

func (*Store) UpdateUser added in v1.4.0

func (s *Store) UpdateUser(ctx context.Context, id uuid.UUID, p domain.UserPatch) (domain.User, error)

UpdateUser applies a patch. It refuses to take away the last enabled global administrator, and disabling a user ends all their sessions and revokes all their API tokens.

func (*Store) UserCredentials added in v1.3.0

func (s *Store) UserCredentials(ctx context.Context, username string) (domain.User, string, error)

UserCredentials returns the user with the given username, ignoring case, and their password hash, which is empty when no password is set.

Directories

Path Synopsis
Package storetest runs integration tests against a real PostgreSQL.
Package storetest runs integration tests against a real PostgreSQL.

Jump to

Keyboard shortcuts

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