models

package
v1.10.2 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ScopeRead   = "read"   // read-only access to resources
	ScopeWrite  = "write"  // create/update/delete resources
	ScopeDeploy = "deploy" // trigger deployments and lifecycle actions
	ScopeAdmin  = "admin"  // administrative operations
	ScopeAll    = "*"      // all scopes
	// Registry-only scopes: a key carrying ONLY these may pull/push images but is
	// rejected by the rest of the API (least-privilege CI/registry credentials).
	ScopeRegistryRead  = "registry_read"  // pull from the container registry
	ScopeRegistryWrite = "registry_write" // push to the container registry
)

API key scopes gate what an API-key caller may do. An empty scope set means read-only (least privilege); "*" grants everything.

View Source
const (
	CanaryMatchSourceHeader = "header"
	CanaryMatchSourceQuery  = "query"
	CanaryMatchSourceCookie = "cookie"
	CanaryMatchSourceIP     = "ip"
)

Canary match sources: where the gateway reads the value a rule compares.

View Source
const (
	CanaryMatchOpEquals      = "equals"
	CanaryMatchOpNotEquals   = "not_equals"
	CanaryMatchOpContains    = "contains"
	CanaryMatchOpNotContains = "not_contains"
	CanaryMatchOpStartsWith  = "starts_with"
	CanaryMatchOpEndsWith    = "ends_with"
	CanaryMatchOpRegex       = "regex"
	CanaryMatchOpIn          = "in"
)

Canary match operators

View Source
const (
	ReloadRestart = "restart"
	ReloadNone    = "none"
)
View Source
const (
	// CertSourceImported is a bring-your-own certificate the user uploaded.
	CertSourceImported = "imported"
	// CertSourceACME is a certificate Miabi issued via ACME DNS-01 using a
	// connected DNS provider (managed; auto-renewable).
	CertSourceACME = "acme"
)

Certificate sources.

View Source
const (
	CertStatusActive  = "active"  // issued and in use
	CertStatusIssuing = "issuing" // issuance in progress
	CertStatusFailed  = "failed"  // last issuance/renewal failed (see LastError)
)

Managed-certificate (ACME) statuses.

View Source
const (
	DNSProviderCloudflare   = "cloudflare"
	DNSProviderRoute53      = "route53"
	DNSProviderDigitalOcean = "digitalocean"
)

DNS provider types Miabi can connect to. Each maps to a libdns module; the credential shape differs per type (see the dns package). "manual" is the implicit default for a domain with no connected provider (copy-paste flow).

View Source
const (
	DNSProviderStatusOK    = "ok"
	DNSProviderStatusError = "error"
)

DNSProviderStatus is the last-known health of a connection.

View Source
const (
	DNSRecordPurposeVerification = "verification" // _miabi-challenge ownership TXT
	DNSRecordPurposeAppAddress   = "app-address"  // app A/AAAA/CNAME
)

DNSRecord purposes — why Miabi created a managed record.

View Source
const (
	NotificationKindAlert        = "alert"
	NotificationKindInfo         = "info"
	NotificationKindAnnouncement = "announcement"
)

Notification kinds. An inbox item is either the delivery of an Alert, a platform announcement, or a standalone informational note.

View Source
const (
	JobSourceManual    = "manual"
	JobSourceAPI       = "api"
	JobSourceScheduled = "scheduled"
)

Job sources.

View Source
const (
	ConcurrencyAllow   = "allow"   // always spawn a new Job
	ConcurrencyForbid  = "forbid"  // skip the tick if a run is still active
	ConcurrencyReplace = "replace" // cancel the in-flight run, then spawn
)

CronJob concurrency policies (Kubernetes parity): what to do when a tick fires while the previous run is still active.

View Source
const (
	LDAPTLSNone     = "none"     // plain LDAP (discouraged; dev/LAN only)
	LDAPTLSStartTLS = "starttls" // upgrade a plain connection with StartTLS
	LDAPTLSLDAPS    = "ldaps"    // implicit TLS (usually port 636)
)

LDAP TLS modes for the directory connection.

View Source
const (
	MetaManagedBy       = "miabi.io/managed-by"       // origin: see ManagedBy* values
	MetaTemplate        = "miabi.io/template"         // marketplace template slug
	MetaTemplateVersion = "miabi.io/template-version" // marketplace template version
	MetaTemplateInstall = "miabi.io/template-install" // template install id
	MetaStack           = "miabi.io/stack"            // owning stack docker name
	MetaGitOpsSource    = "miabi.io/gitops-source"    // id of the GitOps project that created the resource
	// MetaRuntimeAutoService marks an app whose service runtime was auto-defaulted by cluster
	// mode rather than chosen. One-shot: the first deploy re-evaluates (downgrading to a
	// container if the app holds node-local state) then clears it. Value: "true".
	MetaRuntimeAutoService = "miabi.io/runtime-auto-service"
	// MetaDeclarativeName records the manifest resource name a logical database was provisioned
	// for. A manifest Database may be a dedicated instance or share one, so this maps the name
	// back to the exact logical database it owns instead of guessing.
	MetaDeclarativeName = "miabi.io/declarative-name"

	// Owner reference: the entity this resource belongs to, whose lifecycle it follows. Distinct
	// from managed-by (the mechanism of creation); owner is the parent, stored as kind+id+name so
	// the UI can link to it without a join. See OwnerKind* and SetOwner/Owner.
	MetaOwnerKind = "miabi.io/owner-kind" // one of OwnerKind* values
	MetaOwnerID   = "miabi.io/owner-id"   // numeric id of the owner (omitted when 0)
	MetaOwnerName = "miabi.io/owner-name" // owner display name (for rendering + linking)
)

Built-in metadata keys (all under MetadataReservedPrefix).

View Source
const (
	ManagedByUser        = "user"         // created by hand
	ManagedByMarketplace = "marketplace"  // installed from a marketplace template
	ManagedByStack       = "stack"        // created as part of a stack
	ManagedByStackImport = "stack-import" // created by importing a compose file
	ManagedByGitOps      = "gitops"       // created/reconciled by the declarative apply engine
)

ManagedBy values record how a resource came to exist.

View Source
const (
	OwnerUser     = "user"     // a person created it for their own use (owner id = user id)
	OwnerApp      = "app"      // it backs an application
	OwnerDatabase = "database" // it backs a database instance
	OwnerStack    = "stack"    // it belongs to a stack
	// OwnerTemplateInstall marks a resource a marketplace install created and
	// owns, so a template upgrade updates it and an uninstall removes it.
	OwnerTemplateInstall = "template-install"
)

OwnerKind values classify what a resource belongs to (the MetaOwnerKind value).

View Source
const (
	NetAllocKindWorkspace = "workspace" // a workspace's default/user network
	NetAllocKindStack     = "stack"     // a per-stack network
	NetAllocKindGateway   = "gateway"   // the shared reverse-proxy network
	NetAllocKindOverlay   = "overlay"   // a per-workspace swarm overlay
	// NetAllocKindReserved marks a subnet that is not Miabi's but overlaps the pool
	// (a pre-existing/unmanaged Docker network), so the allocator never hands it out.
	NetAllocKindReserved = "reserved"
)

Network-allocation kinds, recorded for observability and to distinguish real managed networks from subnets merely reserved to avoid an overlap.

View Source
const (
	ConfigBotToken   = "bot_token"   // telegram; encrypted at rest
	ConfigChatID     = "chat_id"     // telegram
	ConfigWebhookURL = "webhook_url" // slack/discord; encrypted at rest
)

Config keys used by the channel types.

View Source
const (
	// SecurityProfileDefault runs containers as the image's default user with no
	// extra hardening — the platform's historical behavior.
	SecurityProfileDefault = "default"
	// SecurityProfileRestricted forces app/job containers to run as the platform
	// non-root UID (UID:0) with no-new-privileges and NET_RAW dropped — like
	// OpenShift's restricted SCC. May break images that require root.
	SecurityProfileRestricted = "restricted"
)

SecurityProfile values harden how a workspace's application and job containers run. The zero value ("") is treated as SecurityProfileDefault, which keeps the Plan model's GORM zero-value-omission invariant intact (see the limits block).

View Source
const (
	DefaultDatabaseBackupPath = "databases"
	DefaultVolumeBackupPath   = "volumes"
)

Platform backup object-path defaults. An operator who does not care where the artifacts land should still get a tidy, predictable bucket layout rather than everything piled at the root.

View Source
const (
	RegistryStorageFilesystem = "filesystem"
	RegistryStorageS3         = "s3"
)

Registry storage driver values for RegistrySettings.StorageType.

View Source
const (
	ResourceTypeApp      = "app"
	ResourceTypeDatabase = "database"
	ResourceTypeDomain   = "domain"
)

Resource types a per-resource policy may target.

View Source
const (
	SIEMSinkSyslog  = "syslog"
	SIEMSinkWebhook = "webhook"
	SIEMSinkS3      = "s3"
)

SIEM sink kinds.

View Source
const (
	SIEMFormatJSON = "json" // NDJSON
	SIEMFormatCEF  = "cef"  // syslog CEF
)

SIEM payload formats.

View Source
const (
	LocaleEnglish = "en"
	LocaleFrench  = "fr"
)

Display languages the console ships. Keep in step with web/src/i18n/languages.ts, which is what the Preferences picker renders.

View Source
const (
	VolumeDriverLocal = "local"
	VolumeDriverNFS   = "nfs"
	VolumeDriverCIFS  = "cifs"
	// VolumeDriverHost is a bind to an operator-managed host path (under /mnt/*), not a Docker
	// volume. It is for storage mounted at the SAME path on every node, so a replicated service
	// can share it; AccessMode is rwx. Privileged workspaces only; HostPath carries the path.
	VolumeDriverHost = "host"
)

Volume driver names Miabi understands. The NFS/CIFS variants use Docker's built-in local driver with mount options (no external plugin required).

View Source
const (
	BundlePhaseState     = "state"     // collecting configuration + secrets
	BundlePhaseDatabases = "databases" // dumping / restoring managed databases
	BundlePhaseVolumes   = "volumes"   // archiving / restoring volumes
	BundlePhaseUpload    = "upload"    // sealing and writing the state + info files
	BundlePhaseDone      = "done"
)

Bundle phases, in the order a run passes through them. They are display state, not a state machine: a phase is recorded as work starts so a run that stalls says where, which is the question asked of a long backup.

View Source
const CapabilityAll = "ALL"

CapabilityAll names every capability in a drop.

View Source
const DatabaseBackupSetRefPrefix = "mbdb_"

DatabaseBackupSetRefPrefix marks a database recovery point, the way dr.RefPrefix marks a platform one.

View Source
const DefaultBundlePath = "bundles"

DefaultBundlePath is where bundles live when the workspace sets no prefix.

View Source
const DefaultClusterID uint = 0

DefaultClusterID stands for the default cluster wherever a cluster id is 0, the way ServerID 0 stands for the local node.

View Source
const DefaultOrganizationName = "default"

DefaultOrganizationName is the handle of the seeded default organization.

View Source
const DefaultRegistryVolume = "mb-registry-data"

DefaultRegistryVolume is the managed data volume for the filesystem driver.

View Source
const DefaultStorageClassName = "default"

DefaultStorageClassName is the seeded class every install has: it creates volumes the way Docker does, in the engine's own data root. Its Path is empty, which is the instruction "add no bind driver options".

View Source
const KEKFingerprintLabel = "dr:kek-fingerprint"

KEKFingerprintLabel is the fixed crypto.DeriveToken label for the master-key fingerprint recorded on a set. It is a constant because changing it would make every existing recovery point unverifiable.

View Source
const MaxCapabilities = 12

MaxCapabilities and MaxDevices bound one application's request, so a manifest cannot ask for the whole list.

View Source
const MaxDevices = 8
View Source
const MaxServiceReplicas = 100

MaxServiceReplicas caps a service app's replica count so a single request can't ask Swarm to schedule an unbounded number of tasks (node resource-exhaustion DoS).

View Source
const MetadataReservedPrefix = "miabi.io/"

MetadataReservedPrefix marks built-in, platform-managed metadata keys.

View Source
const PoolLabel = "miabi.pool"

PoolLabel is the node label naming the pool a node belongs to, mirrored onto its Swarm node.

View Source
const RestorePendingKey = "dr.restore_pending"

RestorePendingKey is the setting `miabi restore` writes before the restored control plane's first boot. While true the platform runs quiesced — no schedules, no auto-deploys — so it cannot race to reconcile against DNS still pointing at the host it was recovered from.

View Source
const Unlimited = -1

Unlimited is the limit value meaning "no cap". Distinct from 0 ("none allowed"), so a plan can forbid a resource entirely.

View Source
const UnlimitedPlanName = "Unlimited"

UnlimitedPlanName is the name of the built-in plan with no limits and all capabilities (seeded by SeedPlans). The platform system workspace is pinned to it so platform-managed infrastructure is never constrained by quotas.

Variables

CanaryMatchSources / CanaryMatchOperators are the canonical, ordered lists, shared by validation, the API schema and the console.

View Source
var (
	ErrGrantsDisabled       = errors.New("attaching capabilities and devices is disabled on this platform (MIABI_CONTAINER_GRANTS_ENABLED)")
	ErrCapabilityUnknown    = errors.New("that Linux capability is not one Miabi can grant")
	ErrCapabilityElevated   = errors.New("that capability is close to full host access and is limited to the platform's system workspace")
	ErrCapabilityRestricted = errors.New("this workspace runs the restricted security profile, which does not allow extra capabilities")
	ErrDeviceUnknown        = errors.New("that host device is not one Miabi can expose")
	ErrDeviceBlockDevice    = errors.New("raw block devices expose the host's filesystem and are never granted")
	ErrTooManyCapabilities  = errors.New("too many capabilities requested")
	ErrTooManyDevices       = errors.New("too many devices requested")
	ErrDevicesOnService     = errors.New("host devices cannot be attached to a replicated service; run the app as a container instead")
	ErrCapabilityNotLinux   = errors.New("that is not a Linux capability")
	ErrCapabilityConflict   = errors.New("a capability cannot be both added and dropped")
)

Capability and device errors. Surfaced to the user, so they read as guidance.

View Source
var (
	ErrRunAsUserInvalid = errors.New(`run-as user must be "uid", "uid:gid", "name" or "name:group"`)
	ErrRunAsUserRoot    = errors.New("run-as user must be a non-root numeric uid under the restricted security profile")
)

RunAsUser errors. Both are surfaced to the user, so they read as guidance.

View Source
var ErrStorageClassName = errors.New("a storage class name is lowercase letters, digits and hyphens (max 32), e.g. ssd-fast")

ErrStorageClassName is returned for a class name that is not a short lowercase slug.

View Source
var ErrStorageClassPath = errors.New("storage class path must be a clean absolute path outside the system directories")

ErrStorageClassPath is returned for a class path that is not absolute, not clean, or names a system tree Miabi refuses to write volumes into.

NotifiableEvents is the curated set of lifecycle events that webhooks and notification channels may subscribe to. Configuration changes and other timeline noise are intentionally excluded. Routine database transitions (started/stopped/restarted) are left out for the same reason: only outcomes worth waking someone for are here.

ValidScopes is the set of scopes accepted on API-key creation.

Functions

func AccentCodes added in v1.9.6

func AccentCodes() []string

AccentCodes lists every accent, so an API can offer exactly what the console can render rather than restating the list somewhere it can drift.

func CheckCapabilityConflict added in v1.10.0

func CheckCapabilityConflict(add, drop []string) error

CheckCapabilityConflict refuses a capability both added and dropped by name. Dropping ALL while adding some is the intended way to keep only those, so it is no conflict. Both sets must be normalized.

func ComposeImageRef

func ComposeImageRef(image, tag string) string

ComposeImageRef appends tag (defaulting to "latest") to a bare image, leaving refs that already specify a tag or digest untouched.

func EngineSupportsLogicalDatabases

func EngineSupportsLogicalDatabases(e DBEngine) bool

EngineSupportsLogicalDatabases reports whether an engine can host named per-app databases with their own users (the SQL engines, plus MongoDB which has databases with scoped users). Redis cannot.

func EngineUsesLogicalDatabaseRecord

func EngineUsesLogicalDatabaseRecord(e DBEngine) bool

EngineUsesLogicalDatabaseRecord reports whether an engine hangs backups and app connection injection off a logical Database row: EngineSupportsLogicalDatabases plus libSQL, which gets one implicit row so the per-database pipeline is reused. Only Redis is excluded.

func IsNotifiable

func IsNotifiable(t AppEventType) bool

IsNotifiable reports whether an event type may trigger outbound notifications.

func IsReservedMetadataKey

func IsReservedMetadataKey(key string) bool

IsReservedMetadataKey reports whether key is platform-managed (built-in).

func IsValidPermission

func IsValidPermission(p Permission) bool

IsValidPermission reports whether p is a known catalogued permission.

func IsValidResourceType

func IsValidResourceType(t string) bool

IsValidResourceType reports whether t is a supported resource type.

func IsValidSIEMSink

func IsValidSIEMSink(s string) bool

IsValidSIEMSink reports whether s is a supported sink kind.

func NewDatabaseBackupSetRef added in v1.9.6

func NewDatabaseBackupSetRef(instance string, at time.Time) string

NewDatabaseBackupSetRef builds a set's stable name from the instance it came from and the moment it started: "mbdb_<instance>_20260909T030000Z".

func NormalizeCapabilities added in v1.9.6

func NormalizeCapabilities(in []string) ([]string, error)

NormalizeCapabilities cleans, de-duplicates and sorts a set. Sorted so a no-op save does not read as a change.

func NormalizeCapability added in v1.9.6

func NormalizeCapability(v string) string

NormalizeCapability upper-cases a name and strips the CAP_ prefix people type.

func NormalizeDevices added in v1.9.6

func NormalizeDevices(in []string) ([]string, error)

NormalizeDevices cleans and de-duplicates a device list against the allow-list.

func NormalizeDropCapabilities added in v1.10.0

func NormalizeDropCapabilities(in []string) ([]string, error)

NormalizeDropCapabilities cleans, de-duplicates and sorts the capabilities to drop. ALL already covers every other name, so it is kept alone.

func NormalizeRunAsUser added in v1.8.3

func NormalizeRunAsUser(v string) (string, error)

NormalizeRunAsUser trims a run-as user and validates its shape. The empty string is valid and means "run as the image's own user".

func NormalizeSecurityProfile

func NormalizeSecurityProfile(p string) string

NormalizeSecurityProfile maps the empty/zero value to the default profile.

func PoolOf added in v1.10.0

func PoolOf(s *Server) string

PoolOf is the pool a node belongs to; empty when it is in none.

func ResolveLocale added in v1.9.6

func ResolveLocale(l string) string

ResolveLocale maps a stored value onto a shipped language: the code itself, then its primary subtag ("fr-CA" is French), then English. Rows saved while Language was a free-text field hold arbitrary BCP 47 tags.

func RoleHasPermission

func RoleHasPermission(role WorkspaceRole, p Permission) bool

RoleHasPermission reports whether a built-in role grants a permission.

func RolePermissions

func RolePermissions(role WorkspaceRole) map[Permission]bool

RolePermissions returns the permission set of a built-in role as a copy.

func RunAsUserIsNonRoot added in v1.8.3

func RunAsUserIsNonRoot(v string) bool

RunAsUserIsNonRoot reports whether v pins the container to a non-root account that the platform can verify. Only a numeric uid qualifies: a name is resolved from the image's own /etc/passwd, which the workload controls, so "appuser" is free to be uid 0. A numeric gid is required for the same reason, but gid 0 is allowed — it is the arbitrary-uid convention the restricted profile itself uses.

func SourceOwnedElsewhere added in v1.8.0

func SourceOwnedElsewhere(m Metadata) (owner string, owned bool)

SourceOwnedElsewhere reports whether an application's source (its image or repository) is owned by an external source of truth, and by which. Editing it interactively would be overwritten — by the next GitOps sync — or would break the upgrade path a marketplace template depends on, so the interactive API refuses and points at the right place instead.

This is a HANDLER-level rule, not a service one: the GitOps engine and the marketplace installer both write through the same service, and guarding there would block them from managing the very resources they own.

func SplitImageRef

func SplitImageRef(ref string) (image, tag string)

SplitImageRef is the inverse of ComposeImageRef: it splits a pull reference into its repository and tag (e.g. "ghcr.io/org/app:v2" -> "ghcr.io/org/app", "v2"). A digest-pinned ref is returned as the image with an empty tag.

func ValidAccent added in v1.9.6

func ValidAccent(a Accent) bool

ValidAccent reports whether a is an accent the console ships. Keep in step with web/src/theme/accents.json, which is what actually renders them.

func ValidAccessMode

func ValidAccessMode(m ServerAccessMode) bool

ValidAccessMode reports whether m is a known access mode.

func ValidAppBuildMethod

func ValidAppBuildMethod(m AppBuildMethod) bool

ValidAppBuildMethod reports whether m is a known build method.

func ValidCanaryMatchOperator added in v1.9.0

func ValidCanaryMatchOperator(op string) bool

ValidCanaryMatchOperator reports whether op is a comparison the gateway implements.

func ValidCanaryMatchSource added in v1.9.0

func ValidCanaryMatchSource(s string) bool

ValidCanaryMatchSource reports whether s is a source the gateway can read.

func ValidCanaryMode added in v1.9.0

func ValidCanaryMode(m CanaryMode) bool

ValidCanaryMode reports whether m is a known canary mode.

func ValidClusterVisibility added in v1.10.0

func ValidClusterVisibility(v ClusterVisibility) bool

ValidClusterVisibility reports whether v is a known visibility.

func ValidDNSProviderType deprecated

func ValidDNSProviderType(t string) bool

ValidDNSProviderType reports whether t is a known provider type.

Deprecated: the dnscatalog package is the source of truth; call dnscatalog.Get.

func ValidDatabaseSizeName added in v1.10.0

func ValidDatabaseSizeName(n string) bool

ValidDatabaseSizeName reports whether n is a usable size name: a short lowercase slug.

func ValidDeployStrategy

func ValidDeployStrategy(s DeployStrategy) bool

ValidDeployStrategy reports whether s is a known strategy.

func ValidHealthcheckType

func ValidHealthcheckType(t HealthcheckType) bool

ValidHealthcheckType reports whether t is a known healthcheck type.

func ValidImagePullPolicy

func ValidImagePullPolicy(p ImagePullPolicy) bool

ValidImagePullPolicy reports whether p is a known image pull policy.

func ValidLandingView added in v1.9.4

func ValidLandingView(v string) bool

func ValidLocale added in v1.9.6

func ValidLocale(l string) bool

ValidLocale reports whether l is a display language the console ships.

func ValidPoolName added in v1.10.0

func ValidPoolName(p string) bool

ValidPoolName reports whether p is a usable pool name: a short lowercase slug.

func ValidReclaimPolicy added in v1.10.2

func ValidReclaimPolicy(p ReclaimPolicy) bool

ValidReclaimPolicy reports whether p is a known reclaim policy.

func ValidReconcilePolicy added in v1.10.1

func ValidReconcilePolicy(p ReconcilePolicy) bool

ValidReconcilePolicy reports whether p is a known policy.

func ValidRestartPolicy

func ValidRestartPolicy(p RestartPolicy) bool

ValidRestartPolicy reports whether p is a known restart policy.

func ValidRunnerScope

func ValidRunnerScope(s RunnerScope) bool

ValidRunnerScope reports whether s is a known runner scope.

func ValidRuntimeKind

func ValidRuntimeKind(k RuntimeKind) bool

ValidRuntimeKind reports whether k is a known runtime kind.

func ValidServiceEndpointMode added in v1.10.0

func ValidServiceEndpointMode(m ServiceEndpointMode) bool

ValidServiceEndpointMode reports whether m is a known endpoint mode.

func ValidStorageClassName added in v1.10.2

func ValidStorageClassName(n string) bool

ValidStorageClassName reports whether n is a usable class name: a short lowercase slug. The name is immutable and ends up in manifests, so it is validated and refused rather than coerced — an admin who types "SSD Fast" should be told, not silently given "ssd-fast".

func ValidTheme added in v1.9.4

func ValidTheme(t Theme) bool

ValidTheme reports whether t is a known theme.

func ValidVolumeAccessMode

func ValidVolumeAccessMode(m VolumeAccessMode) bool

ValidVolumeAccessMode reports whether m is a known access mode.

func ValidateStorageClassPath added in v1.10.2

func ValidateStorageClassPath(p string) (string, error)

ValidateStorageClassPath cleans p and verifies it is an absolute path that is not a forbidden system tree, returning the cleaned path. An empty path is valid and means the built-in class: Docker's own data root.

Types

type ACMEAccount

type ACMEAccount struct {
	ID       uint   `json:"id" gorm:"primaryKey"`
	CADirURL string `json:"ca_dir_url" gorm:"uniqueIndex;not null"`
	Email    string `json:"email" gorm:"not null"`
	// KeyEnc is the PEM-encoded account private key, crypto.Encrypt'd at rest.
	KeyEnc string `json:"-" gorm:"type:text;not null"`
	// RegistrationJSON is the lego registration.Resource (account URL + body).
	RegistrationJSON string `json:"-" gorm:"type:text"`

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

ACMEAccount is the platform's registered ACME account for a CA directory, reused across all managed-certificate issuance. The account key is encrypted at rest and never returned. Keyed by CADirURL, so switching CA (staging -> production) registers a distinct account.

type APIKey

type APIKey struct {
	ID          uint     `json:"id" gorm:"primaryKey"`
	UserID      uint     `json:"user_id" gorm:"index;not null"`
	WorkspaceID *uint    `json:"workspace_id,omitempty" gorm:"index"`
	Name        string   `json:"name" gorm:"not null"`
	KeyHash     string   `json:"-" gorm:"uniqueIndex;not null"`
	KeyPrefix   string   `json:"key_prefix" gorm:"index;not null"`
	Scopes      []string `json:"scopes" gorm:"serializer:json"`
	AllowedIPs  []string `json:"allowed_ips" gorm:"serializer:json"`
	// ApplicationID narrows an ephemeral job key to a single application: it may
	// act on (deploy) only that app, nothing else in the workspace. nil = the
	// key is not app-bound (ordinary user keys).
	ApplicationID *uint `json:"application_id,omitempty" gorm:"index"`
	// Ephemeral marks a machine-minted, short-lived job/registry credential (issued per runner
	// lease, revoked when the run goes terminal). Ephemeral keys are hidden from the UI, excluded
	// from the MaxAPIKeys quota, and findable by the orphan sweeper.
	Ephemeral  bool       `json:"ephemeral" gorm:"not null;default:false;index"`
	LastUsedAt *time.Time `json:"last_used_at"`
	ExpiresAt  *time.Time `json:"expires_at"`
	Revoked    bool       `json:"revoked" gorm:"default:false;not null"`
	CreatedAt  time.Time  `json:"created_at"`
}

APIKey is a long-lived bearer credential for programmatic access, scoped to a user and (optionally) a workspace.

func (*APIKey) BoundToApp

func (k *APIKey) BoundToApp(appID uint) bool

BoundToApp reports whether the key is restricted to a single application. A caller enforcing the deploy route uses this to reject a job key acting on any app other than the one it was minted for.

func (*APIKey) HasScope

func (k *APIKey) HasScope(s string) bool

HasScope reports whether the key grants the given scope. An empty scope set defaults to read-only; "*" grants everything.

func (*APIKey) IsExpired

func (k *APIKey) IsExpired() bool

IsExpired reports whether the key has passed its expiry.

func (*APIKey) IsRegistryOnly

func (k *APIKey) IsRegistryOnly() bool

IsRegistryOnly reports whether the key's scopes grant only registry access (so it must be refused by the general API). An empty scope set defaults to read, which is a general scope, so it is never registry-only.

func (*APIKey) IsValid

func (k *APIKey) IsValid() bool

IsValid reports whether the key is currently usable (not revoked, not expired).

type Accent added in v1.9.6

type Accent string

Accent is the console's primary colour. A fixed set rather than a free colour: an arbitrary hex cannot be checked for contrast on both grounds, against white button text, or against the semantic ramps — a fixed set is checked once.

const (
	AccentDefault Accent = "default"
	AccentBlue    Accent = "blue"
	AccentIndigo  Accent = "indigo"
	AccentSlate   Accent = "slate"
	AccentOrange  Accent = "orange"
	AccentLime    Accent = "lime"
)

type Alert added in v1.6.0

type Alert struct {
	ID          uint          `json:"id" gorm:"primaryKey"`
	WorkspaceID uint          `json:"workspace_id" gorm:"index;not null"`
	RuleKey     string        `json:"rule_key" gorm:"not null"` // which built-in rule fired
	Category    AlertCategory `json:"category" gorm:"not null"`
	Severity    AlertSeverity `json:"severity" gorm:"not null"`
	State       AlertState    `json:"state" gorm:"not null;default:firing"`

	// DedupKey identifies the condition+subject. The partial unique index in the
	// migration enforces at most one ACTIVE alert per (workspace, dedup_key).
	DedupKey    string `json:"dedup_key" gorm:"not null"`
	SubjectType string `json:"subject_type"`           // app | database | node | route | backup
	SubjectRef  string `json:"subject_ref"`            // stable id/slug of the subject
	SubjectLink string `json:"subject_link,omitempty"` // UI deep-link
	// MinRole is the lowest workspace role that receives this alert (fan-out gate).
	MinRole WorkspaceRole `json:"min_role" gorm:"not null;default:developer"`

	Title  string            `json:"title"`
	Body   string            `json:"body"`
	Count  int64             `json:"count" gorm:"not null;default:1"` // signals folded into this alert
	Labels map[string]string `json:"labels,omitempty" gorm:"serializer:json"`

	FirstSeen  time.Time  `json:"first_seen"`
	LastSeen   time.Time  `json:"last_seen"`
	ResolvedAt *time.Time `json:"resolved_at,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`
}

Alert is a workspace-level, deduplicated condition derived from signals; per-user delivery is a Notification. The dedup key identifies the condition ("crashloop:app:42"), so a repeat signal bumps Count/LastSeen instead of adding a row — 40 crash events become one line.

type AlertCategory added in v1.6.0

type AlertCategory string

AlertCategory groups alerts for role-based fan-out and UI filtering.

const (
	CategoryDeploy   AlertCategory = "deploy"
	CategoryRuntime  AlertCategory = "runtime"
	CategoryDatabase AlertCategory = "database"
	CategoryStorage  AlertCategory = "storage"
	CategoryTLS      AlertCategory = "tls"
	CategoryNode     AlertCategory = "node"
	CategoryCI       AlertCategory = "ci" // runners / pipelines
	CategoryQuota    AlertCategory = "quota"
	CategorySecurity AlertCategory = "security"
)

type AlertSeverity added in v1.6.0

type AlertSeverity string

AlertSeverity ranks an alert's urgency. Only warning/critical notify by default; info lives in the inbox.

const (
	AlertInfo     AlertSeverity = "info"
	AlertWarning  AlertSeverity = "warning"
	AlertCritical AlertSeverity = "critical"
)

type AlertState added in v1.6.0

type AlertState string

AlertState is the alert's lifecycle position. An alert is a small FSM, not a log row: it fires, may be acknowledged, auto-resolves when the condition clears, and is archived after a retention window.

const (
	AlertFiring       AlertState = "firing"
	AlertAcknowledged AlertState = "acknowledged"
	AlertResolved     AlertState = "resolved"
	AlertArchived     AlertState = "archived"
)

func (AlertState) Active added in v1.6.0

func (s AlertState) Active() bool

Active reports whether the alert is still an open condition (firing or acknowledged) — the states the dedup key is unique across.

type AnalyticsRollup added in v1.6.0

type AnalyticsRollup struct {
	ID            uint      `gorm:"primaryKey" json:"-"`
	WorkspaceID   uint      `gorm:"uniqueIndex:idx_arollup,priority:1;not null" json:"workspace_id"`
	ApplicationID uint      `gorm:"uniqueIndex:idx_arollup,priority:2;index" json:"application_id"`
	RouteName     string    `gorm:"uniqueIndex:idx_arollup,priority:3;size:200" json:"route_name"`
	Bucket        time.Time `gorm:"uniqueIndex:idx_arollup,priority:4;index" json:"bucket"` // minute-truncated UTC

	Requests  int64 `json:"requests"`
	BytesIn   int64 `json:"bytes_in"`
	BytesOut  int64 `json:"bytes_out"`
	Status2xx int64 `json:"status_2xx"`
	Status3xx int64 `json:"status_3xx"`
	Status4xx int64 `json:"status_4xx"`
	Status5xx int64 `json:"status_5xx"`

	// Latency histograms (per-bucket counts over analytics.LatencyBoundsMs, with a
	// trailing overflow bucket) + sums for the mean.
	DurationHist []int64 `gorm:"serializer:json" json:"-"`
	UpstreamHist []int64 `gorm:"serializer:json" json:"-"`
	DurationSum  int64   `json:"-"` // milliseconds
	UpstreamSum  int64   `json:"-"`

	// VisitorsHLL is the serialized HyperLogLog sketch of visitor ids for this
	// bucket — mergeable, so a range's uniques is the merge of its buckets.
	VisitorsHLL []byte `json:"-"`

	// Bounded top-K count maps for the categorical breakdowns.
	TopPaths      map[string]int64 `gorm:"serializer:json" json:"-"`
	TopReferrers  map[string]int64 `gorm:"serializer:json" json:"-"`
	TopCountries  map[string]int64 `gorm:"serializer:json" json:"-"`
	TopUAFamilies map[string]int64 `gorm:"serializer:json" json:"-"` // browser family
	TopUserAgents map[string]int64 `gorm:"serializer:json" json:"-"` // raw user-agent string
	TopOS         map[string]int64 `gorm:"serializer:json" json:"-"`
	TopDevice     map[string]int64 `gorm:"serializer:json" json:"-"` // desktop | mobile | tablet | bot
	TopMethods    map[string]int64 `gorm:"serializer:json" json:"-"`

	// BotRequests is the subset of Requests classified as automated (crawlers,
	// scripts) — the rest are treated as human, for the bot-vs-human split.
	BotRequests int64 `json:"-"`
}

AnalyticsRollup is one minute-bucketed aggregate of a route's HTTP traffic, keyed by (workspace, app, route, minute). Percentiles come from the histograms, uniques from a mergeable HLL sketch, Top* are bounded top-K counts. It holds no PII.

type Announcement added in v1.9.5

type Announcement struct {
	ID    uint   `json:"id" gorm:"primaryKey"`
	Title string `json:"title" gorm:"not null"`
	// Message is deliberately not named Body: okapi resolves a request's body by
	// looking for a field named Body, and applies that rule again to the body's own
	// fields — a payload containing "body" binds as an empty struct, silently.
	Message    string        `json:"message"`
	Link       string        `json:"link,omitempty"`
	ActionText string        `json:"action_text,omitempty"`
	Severity   AlertSeverity `json:"severity" gorm:"not null;default:info"`

	Audience AnnouncementAudience `json:"audience" gorm:"not null;default:all"`
	// WorkspaceIDs narrows AudienceWorkspaces; ignored for every other audience.
	WorkspaceIDs []uint `json:"workspace_ids,omitempty" gorm:"serializer:json"`

	// Pinned raises the notice to a banner across the app instead of leaving it to
	// rest in the bell. Reserve it for notices that change what a user should do
	// right now. How the banner goes away is Dismissal's business.
	Pinned bool `json:"pinned" gorm:"not null;default:false"`
	// Dismissal governs the banner's close control; it means nothing unless Pinned.
	Dismissal AnnouncementDismissal `json:"dismissal" gorm:"not null;default:once"`

	// PublishAt schedules the broadcast; nil means it went out on creation.
	PublishAt *time.Time `json:"publish_at,omitempty"`
	// ExpiresAt retires the notice: the banner stops rendering and the inbox rows
	// stop counting as open. A maintenance window that has passed should not need
	// an operator to come back and clean it up.
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
	PublishedAt *time.Time `json:"published_at,omitempty"`

	// Recipients is how many inbox rows the broadcast has produced so far. It grows
	// as SyncUser backfills users who joined after the broadcast.
	Recipients int    `json:"recipients" gorm:"not null;default:0"`
	CreatedBy  uint   `json:"created_by" gorm:"not null"`
	AuthorName string `json:"author_name"`

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

	// Status is derived, not stored; it is what the admin list renders.
	Status AnnouncementStatus `json:"status" gorm:"-"`
}

Announcement is a platform notice written by an administrator and delivered to each recipient's inbox as a Notification. It is kept separately from the deliveries it produced so the operator can still see, edit or retract what was sent — none of which a pile of per-user rows allows.

func (*Announcement) Live added in v1.9.5

func (a *Announcement) Live(now time.Time) bool

Live reports whether the announcement is published and not yet expired — the state in which it may still be delivered to a user who has not received it.

func (*Announcement) State added in v1.9.5

func (a *Announcement) State(now time.Time) AnnouncementStatus

State derives the announcement's lifecycle position at now.

type AnnouncementAudience added in v1.9.5

type AnnouncementAudience string

AnnouncementAudience selects who a broadcast reaches. Miabi is multi-tenant, so "everyone" is rarely the right blast radius: a maintenance window concerns the workspaces it affects, a licensing change the people who can act on it.

const (
	// AudienceAll reaches every active user.
	AudienceAll AnnouncementAudience = "all"
	// AudienceAdmins reaches the platform super-admins only.
	AudienceAdmins AnnouncementAudience = "admins"
	// AudienceOwners reaches users who own or administer at least one workspace —
	// the people who can act on a platform change.
	AudienceOwners AnnouncementAudience = "owners"
	// AudienceWorkspaces reaches the members of the workspaces listed in WorkspaceIDs.
	AudienceWorkspaces AnnouncementAudience = "workspaces"
)

func (AnnouncementAudience) Valid added in v1.9.5

func (a AnnouncementAudience) Valid() bool

Valid reports whether a is a known audience.

type AnnouncementDismissal added in v1.9.6

type AnnouncementDismissal string

AnnouncementDismissal decides how a pinned notice retires for the reader. It is one field rather than a pair of flags so the combinations that mean nothing cannot be expressed, and so a further presentation can be added as a value.

const (
	DismissOnce  AnnouncementDismissal = "once"
	DismissNever AnnouncementDismissal = "never"
)

func (AnnouncementDismissal) Valid added in v1.9.6

func (d AnnouncementDismissal) Valid() bool

Valid reports whether d is a known dismissal mode.

type AnnouncementStatus added in v1.9.5

type AnnouncementStatus string

AnnouncementStatus is the derived lifecycle position shown in the admin list.

const (
	AnnouncementScheduled AnnouncementStatus = "scheduled"
	AnnouncementPublished AnnouncementStatus = "published"
	AnnouncementExpired   AnnouncementStatus = "expired"
)

type AppBuildMethod

type AppBuildMethod string

AppBuildMethod selects how a git-source application's image is built. It only applies to git apps (image apps pull a prebuilt image).

const (
	// BuildAuto inspects the cloned repository at build time: a Dockerfile in the
	// tree builds with Docker, otherwise Cloud Native Buildpacks build it. Default.
	BuildAuto AppBuildMethod = "auto"
	// BuildDockerfile always builds the repo's Dockerfile.
	BuildDockerfile AppBuildMethod = "dockerfile"
	// BuildBuildpack always builds with Cloud Native Buildpacks (no Dockerfile
	// required); the resulting image runs via the CNB launcher.
	BuildBuildpack AppBuildMethod = "buildpack"
)

type AppEnvVar

type AppEnvVar struct {
	ID            uint      `json:"id" gorm:"primaryKey"`
	ApplicationID uint      `json:"application_id" gorm:"index:idx_env_app_key,unique;not null"`
	Key           string    `json:"key" gorm:"index:idx_env_app_key,unique;not null"`
	Value         string    `json:"value"` // plaintext for non-secret; ciphertext when IsSecret
	IsSecret      bool      `json:"is_secret" gorm:"not null;default:false"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

AppEnvVar is an environment variable for an application. Secret values are encrypted at rest.

type AppEvent

type AppEvent struct {
	ID          uint             `json:"id" gorm:"primaryKey"`
	WorkspaceID uint             `json:"workspace_id" gorm:"index;not null"`
	SubjectType EventSubjectType `json:"subject_type" gorm:"not null;default:app"`
	// ApplicationID is 0 on a non-app event. 0 rather than a nullable pointer because the
	// delivery layer already reads it that way (notify.appLabel treats 0 as "no application").
	ApplicationID uint              `json:"application_id" gorm:"index:idx_event_app_id;not null;default:0"`
	DatabaseID    uint              `json:"database_id,omitempty" gorm:"index:idx_event_db_id;not null;default:0"`
	Type          AppEventType      `json:"type" gorm:"not null"`
	Severity      AppEventSeverity  `json:"severity" gorm:"not null;default:info"`
	Message       string            `json:"message"`
	Metadata      map[string]string `json:"metadata,omitempty" gorm:"serializer:json"`
	ActorID       *uint             `json:"actor_id,omitempty"`
	CreatedAt     time.Time         `json:"created_at" gorm:"index:idx_event_app_id;index:idx_event_db_id"`

	// Display fields are populated at delivery time (notifications, webhooks) and
	// are never persisted. They let a renderer name the resource instead of
	// showing a bare numeric id. Empty when the resource has been deleted.
	ApplicationName string `json:"application_name,omitempty" gorm:"-"`
	ApplicationSlug string `json:"application_slug,omitempty" gorm:"-"`
	DatabaseName    string `json:"database_name,omitempty" gorm:"-"`
}

AppEvent is a timeline entry for a resource: lifecycle transitions, runtime container events (start/stop/crash/health), and configuration changes. Distinct from AuditLog (user mutations, admin-scoped) and from deployment build logs.

Despite the name it is subject-scoped: SubjectType says which of ApplicationID / DatabaseID is set. The name stays because the type is the outbound webhook contract.

func (*AppEvent) HasSubject added in v1.9.5

func (e *AppEvent) HasSubject() bool

HasSubject reports whether the event names a resource. An event without one cannot be listed, streamed or trimmed, so the recorder drops it.

func (*AppEvent) Subject added in v1.9.5

func (e *AppEvent) Subject() (EventSubjectType, uint)

Subject returns the event's subject type and id, defaulting to the application subject so rows written before SubjectType existed keep behaving as application events.

type AppEventSeverity

type AppEventSeverity string

AppEventSeverity colors an event in the UI.

const (
	SeverityInfo    AppEventSeverity = "info"
	SeverityWarning AppEventSeverity = "warning"
	SeverityError   AppEventSeverity = "error"
)

type AppEventType

type AppEventType string

AppEventType is a coarse classification of an application event.

const (
	EventDeployStarted    AppEventType = "deploy.started"
	EventDeploySucceeded  AppEventType = "deploy.succeeded"
	EventDeployFailed     AppEventType = "deploy.failed"
	EventRollbackStarted  AppEventType = "rollback.started"
	EventReleaseActivated AppEventType = "release.activated"
	EventContainerStarted AppEventType = "container.started"
	EventContainerStopped AppEventType = "container.stopped"
	EventContainerDied    AppEventType = "container.died"
	EventContainerOOM     AppEventType = "container.oom"
	EventContainerHealth  AppEventType = "container.health"
	EventContainerRemoved AppEventType = "container.removed"
	EventEnvUpdated       AppEventType = "env.updated"
	EventDomainAttached   AppEventType = "domain.attached"
	EventDomainVerified   AppEventType = "domain.verified"
	EventVolumeAttached   AppEventType = "volume.attached"
	EventVolumeDetached   AppEventType = "volume.detached"
	EventConfigAttached   AppEventType = "config.attached"
	EventConfigDetached   AppEventType = "config.detached"
	EventSettingsUpdated  AppEventType = "settings.updated"
	EventAppCreated       AppEventType = "app.created"
	EventAppDeleted       AppEventType = "app.deleted"
	// EventPipelineAdopted records the outcome of reading a git app's repository
	// for pipeline-as-code: adopted, or why it fell back to a direct build.
	EventPipelineAdopted AppEventType = "pipeline.adopted"
)
const (
	EventDatabaseProvisioned      AppEventType = "database.provisioned"
	EventDatabaseProvisionFailed  AppEventType = "database.provision_failed"
	EventDatabaseStarted          AppEventType = "database.started"
	EventDatabaseStopped          AppEventType = "database.stopped"
	EventDatabaseRestarted        AppEventType = "database.restarted"
	EventDatabaseUpgraded         AppEventType = "database.upgraded"
	EventDatabaseUpgradeFailed    AppEventType = "database.upgrade_failed"
	EventDatabaseBackupSucceeded  AppEventType = "backup.succeeded"
	EventDatabaseBackupFailed     AppEventType = "backup.failed"
	EventDatabaseRestoreSucceeded AppEventType = "restore.succeeded"
	EventDatabaseRestoreFailed    AppEventType = "restore.failed"
)

Database instance event types. These record outcomes and unattended activity, which is what separates them from AuditLog: the audit log records that a user asked for a restart, this records whether the instance came back.

const (
	EventDriftDetected AppEventType = "drift.detected"
	EventDriftResolved AppEventType = "drift.resolved"
)

Drift event types, recorded by the control manager on the timeline of an app whose workload disappeared from under it, and again once it exists again.

const (
	EventReconcileRedeploy    AppEventType = "reconcile.redeploy"
	EventReconcileBlocked     AppEventType = "reconcile.blocked"
	EventReconcileBreakerOpen AppEventType = "reconcile.breaker_open"
)

Reconcile event types, recorded when the control manager acts on drift — or declines to, which matters just as much: an app left alone because its data is gone has to say so.

type AppMount

type AppMount struct {
	VolumeID   uint   `json:"volume_id"`
	DockerName string `json:"docker_name"`
	Path       string `json:"path"`
	HostPreset string `json:"host_preset,omitempty"`

	HostPath string `json:"host_path,omitempty"`

	ConfigID  uint   `json:"config_id,omitempty"`
	ConfigKey string `json:"config_key,omitempty"`
	Mode      string `json:"mode,omitempty"`
	ReadOnly  bool   `json:"read_only,omitempty"`
}

type AppPort

type AppPort struct {
	ID            uint   `json:"id" gorm:"primaryKey"`
	ApplicationID uint   `json:"application_id" gorm:"index:idx_appport_unique,unique;not null"`
	ContainerPort int    `json:"container_port" gorm:"index:idx_appport_unique,unique;not null"`
	Protocol      string `json:"protocol" gorm:"index:idx_appport_unique,unique;not null;default:tcp"` // tcp | udp
	// Scheme is the application protocol the container speaks on this port
	// (http | https), used to build the Gateway backend URL. Transport stays in
	// Protocol; this is L7. Defaults to http.
	Scheme string `json:"scheme" gorm:"not null;default:http"`
	Name   string `json:"name"`
}

AppPort is a container port an application exposes. Developer-managed; no approval is required to declare one.

type AppSourceType

type AppSourceType string

AppSourceType is how an application's image is obtained.

const (
	AppSourceImage AppSourceType = "image" // pull a prebuilt image
	AppSourceGit   AppSourceType = "git"   // build from a Git repo
)

type AppStatus

type AppStatus string

AppStatus is the high-level state of an application.

const (
	AppStatusCreated   AppStatus = "created"
	AppStatusDeploying AppStatus = "deploying"
	AppStatusRunning   AppStatus = "running"
	AppStatusStopped   AppStatus = "stopped"
	AppStatusFailed    AppStatus = "failed"
)

type Application

type Application struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_app_workspace_name,unique;not null"`
	// Name is the unique, URL/CLI/docker handle (lowercase [a-z0-9-]) scoped to
	// the workspace; the numeric ID/UID remain the stable internal references.
	Name string `json:"name" gorm:"index:idx_app_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string        `json:"display_name"`
	SourceType  AppSourceType `json:"source_type" gorm:"not null;default:image"`
	// Alias is the stable in-network DNS name and container hostname, "mb-app-<token>-<id>".
	// Generated once at creation and reused as the proxy upstream, so it survives redeploys.
	// Empty on legacy apps, which fall back to "mb-app-<id>".
	Alias string `json:"alias,omitempty" gorm:"index"`
	// ServerID is the node this app runs on (0 = local control-plane node). In
	// cluster mode (RuntimeService) it is a placement hint rather than a fixed
	// node — Swarm schedules the tasks subject to PlacementConstraints.
	ServerID  uint `json:"server_id" gorm:"index;not null;default:0"`
	ClusterID uint `json:"cluster_id" gorm:"index;not null;default:0"`
	// ServerName is the display name of the node (transient; populated on read so
	// the UI can show where the app runs). Empty if the node is unknown.
	ServerName string `json:"server_name,omitempty" gorm:"-"`
	// Nodes is the real per-node replica placement of a cluster (RuntimeService) app. Transient:
	// populated only on the app-detail read, and only in cluster mode. Empty for container apps,
	// whose single node is ServerName.
	Nodes []NodePlacement `json:"nodes,omitempty" gorm:"-"`

	// Cluster runtime. "container" (default) is a single container on plain Docker; "service"
	// runs a replicated Swarm service on the workspace overlay when cluster mode is enabled.
	// Replicas, PlacementConstraints and UpdateConfig apply only to the service runtime.
	RuntimeKind          RuntimeKind          `json:"runtime_kind" gorm:"not null;default:container"`
	Replicas             int                  `json:"replicas" gorm:"not null;default:1"`
	PlacementConstraints []string             `json:"placement_constraints,omitempty" gorm:"serializer:json"`
	UpdateConfig         *ServiceUpdateConfig `json:"update_config,omitempty" gorm:"serializer:json"`

	// Icon is an optional logo for the app (a URL or an "mdi-…" class) shown in
	// the UI. Set from a marketplace template on install; empty for ad-hoc apps,
	// which fall back to a generated avatar.
	Icon string `json:"icon,omitempty"`

	// Image source. Image is the repository (e.g. "nginx", "ghcr.io/org/app");
	// Tag is optional and defaults to "latest" when composing the pull ref.
	Image string `json:"image"`
	Tag   string `json:"tag,omitempty"`

	GitRepo string `json:"git_repo,omitempty"`
	GitRef  string `json:"git_ref,omitempty"`

	// Build config (git source only). BuildMethod selects auto/dockerfile/buildpack; Builder
	// overrides the buildpack builder image; Buildpacks pins extras; BuildEnv supplies build
	// arguments. All are ignored for image-source apps.
	BuildMethod AppBuildMethod    `json:"build_method,omitempty" gorm:"not null;default:auto"`
	Builder     string            `json:"builder,omitempty"`
	Buildpacks  []string          `json:"buildpacks,omitempty" gorm:"serializer:json"`
	BuildEnv    map[string]string `json:"build_env,omitempty" gorm:"serializer:json"`

	// CacheGeneration names the app's current build cache; bumping it is what "invalidate the build
	// cache" does. It is part of the registry cache ref, so a bump points builds at a ref that does
	// not exist yet rather than deleting anything.
	CacheGeneration uint `json:"cache_generation" gorm:"not null;default:0"`
	// CacheBuiltGeneration is the generation the last successful build produced. While it trails
	// CacheGeneration the next build is forced cold — the only way to reach a runner whose cache is
	// its local daemon and has no ref to rotate.
	CacheBuiltGeneration uint `json:"cache_built_generation" gorm:"not null;default:0"`

	// Credentials. RegistryID selects a stored registry credential used to pull
	// private images; GitRepositoryID selects a stored Git credential used to
	// clone private repos. Both nil = anonymous (public) source.
	RegistryID      *uint `json:"registry_id,omitempty" gorm:"index"`
	GitRepositoryID *uint `json:"git_repository_id,omitempty" gorm:"index"`

	// StackID optionally groups the app under a Stack (nil = ungrouped). When
	// set, the stack's DockerName is applied to the app's containers as the
	// Docker Compose project label.
	StackID *uint `json:"stack_id,omitempty" gorm:"index"`

	// TemplateInstallID links the app back to the marketplace template install it
	// was created from (nil = not installed from a template). Lets the UI show
	// provenance ("installed from <template>") and jump to the install.
	TemplateInstallID *uint `json:"template_install_id,omitempty" gorm:"index"`

	// OfficialTemplate marks an app created from an *official* marketplace template. Set by the
	// platform at install time, never by user input: it is the trust boundary for the
	// AllowOfficialImageUser plan capability.
	OfficialTemplate bool `json:"official_template" gorm:"not null;default:false"`

	// Metadata holds free-form labels (provenance, grouping, declarative/GitOps).
	// Keys under the reserved "miabi.io/" prefix are platform-managed.
	Metadata Metadata `json:"metadata,omitempty" gorm:"serializer:json"`

	// Annotations holds free-form, non-identifying metadata (the manifest's metadata.annotations).
	// Unlike Metadata it is never used for selection or grouping and carries no reserved keys.
	// Persisted as JSON.
	Annotations Metadata `json:"annotations,omitempty" gorm:"serializer:json"`

	// ContainerLabels are user-defined Docker labels stamped onto the app's container(s) at
	// deploy time, for label-driven tools. Keys under Miabi's reserved prefixes (io.miabi.*,
	// miabi.*, com.docker.*) are stripped so they cannot spoof platform labels. Needs a redeploy.
	ContainerLabels map[string]string `json:"container_labels,omitempty" gorm:"serializer:json"`
	// ReloadPolicy decides what a mounted config's content change does: restart
	// (default) redeploys the app, none leaves it running for apps that watch
	// their own config file.
	ReloadPolicy string `json:"reload_policy,omitempty"`

	Command     []string   `json:"command,omitempty" gorm:"serializer:json"`
	Mounts      []AppMount `json:"mounts,omitempty" gorm:"serializer:json"` // attached volumes
	Port        int        `json:"port,omitempty"`                          // primary container port
	MemoryBytes int64      `json:"memory_bytes"`                            // 0 = unlimited
	NanoCPUs    int64      `json:"nano_cpus"`                               // 0 = unlimited; 1 core = 1e9
	// GPUCount is the number of whole GPU units this app requests (0 = none). It
	// is declarative on the app but only consumes quota while the app is running,
	// and is resolved to concrete devices on the app's node at each deploy.
	GPUCount int `json:"gpu_count" gorm:"not null;default:0"`
	// GPUKind narrows the request to a vendor or model when set ("nvidia",
	// "NVIDIA A100-…"); empty = any enabled GPU on the app's node.
	GPUKind string `json:"gpu_kind,omitempty"`
	// RunAsUser overrides the account the container runs as ("uid", "uid:gid", "name", "name:group"),
	// like `docker run --user`. Empty keeps the image's own user. Under the restricted security
	// profile it must be a non-root numeric uid, and it replaces the platform UID rather than
	// escaping it. Managed volumes are chowned to it on deploy; needs a redeploy.
	RunAsUser string `json:"run_as_user,omitempty"`
	// AddCapabilities and Devices are kernel privileges beyond the container
	// default, allow-listed in capabilities.go and gated on the workspace. Empty
	// grants nothing; both need a redeploy.
	AddCapabilities []string `json:"add_capabilities,omitempty" gorm:"serializer:json"`
	Devices         []string `json:"devices,omitempty" gorm:"serializer:json"`
	// ReadOnlyRootFilesystem, NoNewPrivileges and DropCapabilities (ALL for every one) harden the container
	// on top of the workspace's security profile, which they can tighten but never loosen. Need a redeploy.
	ReadOnlyRootFilesystem bool     `json:"read_only_root_filesystem" gorm:"not null;default:false"`
	NoNewPrivileges        bool     `json:"no_new_privileges" gorm:"not null;default:false"`
	DropCapabilities       []string `json:"drop_capabilities,omitempty" gorm:"serializer:json"`
	// RestartPolicy is the Docker restart policy for the app's container.
	// Defaults to unless-stopped (the platform's historical behavior).
	RestartPolicy RestartPolicy `json:"restart_policy" gorm:"not null;default:unless-stopped"`
	// ImagePullPolicy decides whether a deploy pulls the image. Defaults to
	// always (the platform's historical behavior of fetching the tag each deploy).
	ImagePullPolicy ImagePullPolicy `json:"image_pull_policy" gorm:"not null;default:always"`

	// Healthcheck. none disables it; http probes HealthcheckHTTPPath on HealthcheckPort (0 = the
	// app's primary port); command runs HealthcheckCommand via the shell. When set, a deploy
	// waits for the container to report healthy before going live.
	HealthcheckType               HealthcheckType `json:"healthcheck_type" gorm:"not null;default:none"`
	HealthcheckHTTPPath           string          `json:"healthcheck_http_path"`
	HealthcheckPort               int             `json:"healthcheck_port"`
	HealthcheckCommand            string          `json:"healthcheck_command"`
	HealthcheckIntervalSeconds    int             `json:"healthcheck_interval_seconds" gorm:"not null;default:30"`
	HealthcheckTimeoutSeconds     int             `json:"healthcheck_timeout_seconds" gorm:"not null;default:5"`
	HealthcheckRetries            int             `json:"healthcheck_retries" gorm:"not null;default:3"`
	HealthcheckStartPeriodSeconds int             `json:"healthcheck_start_period_seconds" gorm:"not null;default:0"`

	// Imported marks an app adopted from a pre-existing (hand-run / compose)
	// container rather than created through Miabi. It clears on the first
	// native deploy, which recreates the container under Miabi conventions.
	Imported bool `json:"imported" gorm:"not null;default:false"`

	// ExternalLabel is the stable DNS label used for one-click external access
	// (`<label>.<base-domain>`). Generated once on first expose (default
	// `<slug>-<token>`) so the public URL survives renames/redeploys.
	ExternalLabel string `json:"external_label,omitempty" gorm:"index"`

	Status           AppStatus `json:"status" gorm:"not null;default:created"`
	CurrentReleaseID *uint     `json:"current_release_id"`
	// RedeployRequired is set when config changes while the app is stopped (the
	// running container, if any, is stale). Start/Restart then redeploy instead
	// of reusing the old container, and any successful deploy clears it.
	RedeployRequired bool `json:"redeploy_required" gorm:"not null;default:false"`

	// DeployStrategy is the app's default rollout method, applied when a deploy
	// does not specify one. See DeployStrategy constants.
	DeployStrategy DeployStrategy `json:"deploy_strategy" gorm:"not null;default:rolling"`

	// ReconcilePolicy overrides the platform's control-manager mode for this app: leave it out of
	// reconciliation, report it without acting, or let it be redeployed in place. Inherit follows the platform.
	ReconcilePolicy ReconcilePolicy `json:"reconcile_policy" gorm:"not null;default:inherit"`

	// Canary tuning (used when DeployStrategy is canary or a deploy overrides to
	// canary). The platform starts at CanaryInitialWeight and adds
	// CanaryStepWeight every CanaryStepIntervalSeconds until it reaches 100%.
	CanaryInitialWeight       int `json:"canary_initial_weight" gorm:"not null;default:10"`
	CanaryStepWeight          int `json:"canary_step_weight" gorm:"not null;default:20"`
	CanaryStepIntervalSeconds int `json:"canary_step_interval_seconds" gorm:"not null;default:60"`

	// Canary live state. When CanaryReleaseID is set, a canary container runs alongside the
	// stable release and the proxy sends CanaryWeight percent of traffic to it. Cleared on
	// promote/abort and superseded by any normal deploy.
	CanaryReleaseID *uint `json:"canary_release_id,omitempty"`
	CanaryWeight    int   `json:"canary_weight" gorm:"not null;default:0"`

	CanaryMode CanaryMode `json:"canary_mode" gorm:"not null;default:auto"`

	// CanaryPausedAt holds the ramp where it stands; nil means it is advancing.
	CanaryPausedAt *time.Time `json:"canary_paused_at,omitempty"`

	CanaryExclusive bool              `json:"canary_exclusive" gorm:"not null;default:false"`
	CanaryPriority  int               `json:"canary_priority" gorm:"not null;default:0"`
	CanaryMatch     []CanaryMatchRule `json:"canary_match,omitempty" gorm:"serializer:json"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	EnvVars       []AppEnvVar    `json:"env_vars,omitempty" gorm:"foreignKey:ApplicationID"`
	Networks      []Network      `json:"networks,omitempty" gorm:"many2many:application_networks;"`
	Ports         []AppPort      `json:"ports,omitempty" gorm:"foreignKey:ApplicationID"`
	Stack         *Stack         `json:"stack,omitempty" gorm:"foreignKey:StackID;constraint:OnDelete:SET NULL"`
	Registry      *Registry      `json:"-" gorm:"foreignKey:RegistryID;constraint:OnDelete:SET NULL"`
	GitRepository *GitRepository `json:"-" gorm:"foreignKey:GitRepositoryID;constraint:OnDelete:SET NULL"`
}

Application is a deployable workload owned by a workspace.

func (*Application) BeforeCreate added in v1.10.0

func (a *Application) BeforeCreate(tx *gorm.DB) error

func (*Application) ImageRef

func (a *Application) ImageRef(tagOverride string) string

ImageRef composes the effective pull reference from Image and Tag; tagOverride wins when non-empty. An image already carrying a tag or digest is used verbatim, otherwise the tag (or "latest") is appended.

type AuditLog

type AuditLog struct {
	ID          uint           `json:"id" gorm:"primaryKey"`
	ActorID     *uint          `json:"actor_id" gorm:"index"`
	WorkspaceID *uint          `json:"workspace_id" gorm:"index"`
	Action      string         `json:"action" gorm:"index;not null"`
	TargetType  string         `json:"target_type"`
	TargetID    string         `json:"target_id"`
	IPAddress   string         `json:"ip_address"`
	Metadata    map[string]any `json:"metadata,omitempty" gorm:"serializer:json"`
	CreatedAt   time.Time      `json:"created_at"`
}

AuditLog is an append-only record of a mutating action.

type Backup

type Backup struct {
	ID uint `json:"id" gorm:"primaryKey"`
	// Number is the per-database sequential backup number, independent of the global ID.
	// Assigned in BeforeCreate; the composite unique index keeps it gap-free per database
	// and prevents duplicates.
	Number      int  `json:"number" gorm:"index:idx_backup_db_number,unique;not null;default:0"`
	WorkspaceID uint `json:"workspace_id" gorm:"index;not null"`
	DatabaseID  uint `json:"database_id" gorm:"index:idx_backup_db_number,unique;index;not null"`
	// SetID names the recovery point this backup belongs to, when it was taken as
	// part of one. Nil for an ordinary single-database backup.
	SetID       *uint        `json:"set_id,omitempty" gorm:"index"`
	Engine      DBEngine     `json:"engine"`
	ServerID    uint         `json:"server_id" gorm:"index;not null;default:0"` // node the backup ran on
	Status      BackupStatus `json:"status" gorm:"not null;default:pending"`
	Trigger     string       `json:"trigger"`               // manual | scheduled
	Destination string       `json:"destination"`           // local | s3
	VolumeName  string       `json:"volume_name,omitempty"` // local destination
	S3Bucket    string       `json:"s3_bucket,omitempty"`   // s3 destination (reference)
	S3Path      string       `json:"s3_path,omitempty"`
	Filename    string       `json:"filename,omitempty"`
	SizeBytes   int64        `json:"size_bytes"`
	// Encrypted records that the artifact was GPG-encrypted with the workspace's
	// backup passphrase, so the history can say which backups need it to restore.
	// Restore still keys off the ".gpg" filename, which is what the tools read.
	Encrypted bool `json:"encrypted" gorm:"not null;default:false"`
	// Version is the engine version the dump was taken from. Recorded because a
	// dump does not always restore into a different major version, and because the
	// question "what was running when this was taken" is the usual one.
	Version string `json:"version,omitempty"`
	// Comment is a free-text note the operator attaches to a backup — "before the
	// v1.3.0 rollout" — so it can be identified later by why it was taken rather
	// than only by when.
	Comment string `json:"comment,omitempty"`
	// Pinned exempts the backup from retention pruning, as it does for a Release.
	// Deliberately separate from Comment: pinning is a decision, not a side effect
	// of writing a note.
	Pinned bool `json:"pinned" gorm:"not null;default:false"`
	// Logs is a bounded tail of the backup output for instant display
	Logs         string     `json:"logs,omitempty" gorm:"type:text"`
	LogRef       string     `json:"log_ref,omitempty"`
	LogBytes     int64      `json:"log_bytes,omitempty"`
	LogLines     int        `json:"log_lines,omitempty"`
	LogTruncated bool       `json:"log_truncated,omitempty"`
	Error        string     `json:"error,omitempty" gorm:"type:text"`
	StartedAt    *time.Time `json:"started_at"`
	FinishedAt   *time.Time `json:"finished_at"`
	CreatedAt    time.Time  `json:"created_at"`
}

Backup is a single backup run of a managed database.

func (*Backup) BeforeCreate added in v1.9.5

func (b *Backup) BeforeCreate(tx *gorm.DB) error

type BackupSchedule

type BackupSchedule struct {
	ID          uint   `json:"id" gorm:"primaryKey"`
	WorkspaceID uint   `json:"workspace_id" gorm:"index;not null"`
	DatabaseID  uint   `json:"database_id" gorm:"index;not null"`
	Cron        string `json:"cron" gorm:"not null"`
	Destination string `json:"destination" gorm:"not null;default:local"`
	Enabled     bool   `json:"enabled" gorm:"not null;default:true"`

	// Retention, applied after each scheduled run. 0 = unlimited.
	MaxBackups    int `json:"max_backups" gorm:"not null;default:0"`    // keep at most N most-recent backups
	RetentionDays int `json:"retention_days" gorm:"not null;default:0"` // delete backups older than N days

	S3Endpoint       string `json:"s3_endpoint,omitempty"`
	S3Bucket         string `json:"s3_bucket,omitempty"`
	S3Region         string `json:"s3_region,omitempty"`
	S3AccessKey      string `json:"s3_access_key,omitempty"`
	S3SecretKeyEnc   string `json:"-" gorm:"column:s3_secret_key_enc"` // encrypted
	S3Path           string `json:"s3_path,omitempty"`
	S3UseSSL         bool   `json:"s3_use_ssl"`
	S3ForcePathStyle bool   `json:"s3_force_path_style"`

	LastRunAt *time.Time `json:"last_run_at"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

BackupSchedule runs backups of a database on a cron schedule. When Destination is "s3", the S3* fields hold the target (secret key encrypted).

type BackupStatus

type BackupStatus string

BackupStatus is the state of a backup run.

const (
	BackupPending   BackupStatus = "pending"
	BackupRunning   BackupStatus = "running"
	BackupCompleted BackupStatus = "completed"
	BackupFailed    BackupStatus = "failed"
)

type BrandAsset added in v1.10.1

type BrandAsset struct {
	Slot        string `gorm:"primaryKey;size:16"`
	ContentType string `gorm:"size:64;not null"`
	SHA256      string `gorm:"column:sha256;size:64;not null"`
	Size        int    `gorm:"not null"`
	Data        []byte `gorm:"not null"`
	UpdatedAt   time.Time
}

BrandAsset is an image the operator uploaded for the brand: a logo or the favicon. Kept in the database rather than on disk, so every control-plane replica serves the same file.

type BundleReport added in v1.7.0

type BundleReport struct {
	Items []BundleReportItem `json:"items,omitempty"`
	// Notes are the manual follow-ups a restore cannot perform itself.
	Notes []string `json:"notes,omitempty"`
}

BundleReport is the outcome of a run, item by item.

func (*BundleReport) Add added in v1.7.0

func (r *BundleReport) Add(kind, name, action, detail string)

Add appends an item to the report.

func (*BundleReport) Failures added in v1.7.0

func (r *BundleReport) Failures() []BundleReportItem

Failures returns the items that did not succeed.

func (*BundleReport) Note added in v1.7.0

func (r *BundleReport) Note(note string)

Note appends a manual follow-up.

type BundleReportItem added in v1.7.0

type BundleReportItem struct {
	Kind   string `json:"kind"`             // app | database | volume | secret | route | …
	Name   string `json:"name"`             //
	Action string `json:"action"`           // captured | created | skipped | failed
	Detail string `json:"detail,omitempty"` // why it was skipped, or what failed
}

BundleReportItem is one resource's outcome.

type CanaryMatchRule added in v1.9.0

type CanaryMatchRule struct {
	Source   string `json:"source"`
	Name     string `json:"name"`
	Operator string `json:"operator"`
	Value    string `json:"value"`
}

CanaryMatchRule is one condition a request must satisfy for the canary backend to be eligible. All of an app's rules must hold (AND), matching the gateway.

type CanaryMode added in v1.9.0

type CanaryMode string

CanaryMode is who moves the canary's traffic weight during a rollout.

const (
	// CanaryModeAuto lets the platform ramp the weight on a timer until the canary
	// reaches 100% and is promoted. Default, and the only mode in Community.
	CanaryModeAuto CanaryMode = "auto"
	// CanaryModeManual holds the weight wherever the user put it: the ramp never
	// moves it, and traffic may additionally be steered by match rules.
	CanaryModeManual CanaryMode = "manual"
)

type Capability added in v1.9.6

type Capability struct {
	Name string         `json:"name"`
	Tier CapabilityTier `json:"tier"`
	Help string         `json:"help"`
}

Capability describes one grantable Linux capability. Help is shown by the control.

func Capabilities added in v1.9.6

func Capabilities() []Capability

Capabilities returns the allow-list.

func LookupCapability added in v1.9.6

func LookupCapability(name string) (Capability, bool)

LookupCapability finds a capability in the allow-list by its normalized name.

type CapabilityTier added in v1.9.6

type CapabilityTier int

CapabilityTier decides which workspaces may grant a capability or device.

const (
	// TierCommon widens what a container may do to itself, not to the host.
	TierCommon CapabilityTier = iota
	// TierElevated is close enough to full host access to need the system workspace.
	TierElevated
)

func HighestCapabilityTier added in v1.9.6

func HighestCapabilityTier(names []string) CapabilityTier

HighestCapabilityTier reports the most privileged tier in a set, to gate once.

func HighestDeviceTier added in v1.9.6

func HighestDeviceTier(paths []string) CapabilityTier

HighestDeviceTier reports the most privileged tier in a normalized device set.

type Certificate

type Certificate struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_cert_workspace_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace.
	Name string `json:"name" gorm:"index:idx_cert_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	CertPEM     string `json:"-" gorm:"type:text"` // leaf + intermediates (PEM)
	KeyEnc      string `json:"-" gorm:"type:text"` // private key, encrypted at rest

	// Parsed metadata (populated on import / replace / issue).
	CommonName string    `json:"common_name"`
	DNSNames   []string  `json:"dns_names" gorm:"serializer:json"` // SANs, for host auto-match
	Issuer     string    `json:"issuer"`
	NotBefore  time.Time `json:"not_before"`
	NotAfter   time.Time `json:"not_after"`
	SerialHex  string    `json:"serial_hex"`

	// Managed (ACME) fields; apply only to "acme" certs (Source defaults to "imported").
	Source        string `json:"source" gorm:"not null;default:imported"` // imported | acme
	DNSProviderID *uint  `json:"dns_provider_id,omitempty" gorm:"index"`  // provider used to issue
	AutoRenew     bool   `json:"auto_renew" gorm:"not null;default:false"`
	Status        string `json:"status" gorm:"not null;default:active"` // active | issuing | failed
	LastError     string `json:"last_error,omitempty"`

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

Certificate is a workspace-scoped TLS certificate; a route with TLSMode=custom references it by CertificateID and the PEM/key are sourced server-side at render time. CertPEM is public; KeyEnc is encrypted at rest and never returned. Metadata is parsed from the leaf.

type Cluster added in v1.10.0

type Cluster struct {
	UIDModel
	ID           uint        `json:"id" gorm:"primaryKey"`
	Name         string      `json:"name" gorm:"uniqueIndex;not null"`
	DisplayName  string      `json:"display_name"`
	LocationCode string      `json:"location_code,omitempty"`
	Mode         ClusterMode `json:"mode" gorm:"not null;default:standalone"`
	IsDefault    bool        `json:"is_default" gorm:"not null;default:false"`
	// ManagerServerID is the node Swarm and engine calls go through; 0 is the local socket.
	ManagerServerID uint   `json:"manager_server_id"`
	AgentTokenHash  string `json:"-"`
	// IngressServerID is the node running the cluster gateway; 0 is the local node.
	IngressServerID uint              `json:"ingress_server_id"`
	IngressIP       string            `json:"ingress_ip,omitempty"`
	IngressHostname string            `json:"ingress_hostname,omitempty"`
	Visibility      ClusterVisibility `json:"visibility" gorm:"not null;default:all"`
	Cordoned        bool              `json:"cordoned" gorm:"not null;default:false"`
	// ExternalBaseDomain is the wildcard domain generated app URLs in this cluster live under, empty when one-click
	// external access is off here; ExternalCertProvider is the gateway's certManager provider for them.
	ExternalBaseDomain   string `json:"external_base_domain,omitempty"`
	ExternalCertProvider string `json:"external_cert_provider,omitempty"`
	// The environment pins the default cluster's external access fields. ExternalApps counts apps with generated URLs.
	ExternalDomainPinned   bool  `json:"external_domain_pinned,omitempty" gorm:"-"`
	ExternalProviderPinned bool  `json:"external_provider_pinned,omitempty" gorm:"-"`
	ExternalApps           int64 `json:"external_apps,omitempty" gorm:"-"`
	// ServiceEndpointMode is how service apps are reached by name; dnsrr serves hosts that cannot run IPVS.
	ServiceEndpointMode ServiceEndpointMode `json:"service_endpoint_mode" gorm:"not null;default:vip"`
	// LegacyIngress marks a cluster whose port-forward node became an edge gateway at upgrade, until an
	// admin confirms that gateway or joins the node to a swarm.
	LegacyIngress bool  `json:"legacy_ingress" gorm:"not null;default:false"`
	NodeCount     int64 `json:"node_count" gorm:"-"`
	// Capacity is the sum of the cluster's nodes, derived on read rather than stored: a second copy
	// of a figure the nodes already carry is a copy that can drift.
	Capacity  *ClusterCapacity `json:"capacity,omitempty" gorm:"-"`
	CreatedAt time.Time        `json:"created_at"`
	UpdatedAt time.Time        `json:"updated_at"`
}

Cluster is a deploy target: nodes that share private networking and one ingress. Tenants see it as a location. Every node belongs to exactly one cluster; the default one holds the control plane.

func (*Cluster) EndpointMode added in v1.10.0

func (c *Cluster) EndpointMode() ServiceEndpointMode

EndpointMode is the cluster's service endpoint mode, a virtual IP when unset.

func (*Cluster) IngressNode added in v1.10.0

func (c *Cluster) IngressNode() uint

IngressNode is the node whose gateway serves the cluster, falling back to its manager.

func (*Cluster) Label added in v1.10.0

func (c *Cluster) Label() string

Label is the cluster's display name, falling back to its handle.

type ClusterCapacity added in v1.10.2

type ClusterCapacity struct {
	Nodes            int64   `json:"nodes"`
	NodesMeasured    int64   `json:"nodes_measured"`
	CPUCores         int64   `json:"cpu_cores"`
	MemoryBytes      int64   `json:"memory_bytes"`
	StorageBytes     int64   `json:"storage_bytes"`
	StorageFreeBytes int64   `json:"storage_free_bytes"`
	NodesWithUsage   int64   `json:"nodes_with_usage"`
	CPUPercent       float64 `json:"cpu_percent"`
	MemUsedBytes     int64   `json:"mem_used_bytes"`
}

ClusterCapacity is what a cluster's nodes add up to, and how much of that is measured. A cluster with unmeasured nodes reports fewer than it has rather than counting them as empty.

type ClusterMode added in v1.10.0

type ClusterMode string

ClusterMode is how a cluster runs its workloads.

const (
	// ClusterModeStandalone is a single plain-Docker node.
	ClusterModeStandalone ClusterMode = "standalone"
	// ClusterModeSwarm is one Docker Swarm of one or more nodes.
	ClusterModeSwarm ClusterMode = "swarm"
)

type ClusterVisibility added in v1.10.0

type ClusterVisibility string

ClusterVisibility decides which workspaces may place resources in a cluster.

const (
	ClusterVisibilityAll        ClusterVisibility = "all"
	ClusterVisibilityRestricted ClusterVisibility = "restricted"
)

type Config added in v1.8.1

type Config struct {
	UIDModel
	ID          uint   `json:"id" gorm:"primaryKey"`
	WorkspaceID uint   `json:"workspace_id" gorm:"index:idx_config_workspace_name,unique;not null"`
	Name        string `json:"name" gorm:"index:idx_config_workspace_name,unique;not null"`
	DisplayName string `json:"display_name"`
	Description string `json:"description"`
	// DataEnc is the encrypted JSON object of key -> content, never returned raw
	// when Sensitive.
	DataEnc string `json:"-" gorm:"column:data_enc;type:text"`
	// Digest is sha256 over the canonical (sorted-key) serialization of the
	// decrypted data. Drives redeploy-on-change and docker object naming.
	Digest    string `json:"digest" gorm:"not null"`
	Mode      string `json:"mode" gorm:"not null;default:0644"`
	Sensitive bool   `json:"sensitive" gorm:"not null;default:false"`
	// Delimiters overrides the interpolation delimiters for this config's values.
	Delimiters []string `json:"delimiters,omitempty" gorm:"serializer:json"`
	// Version bumps on each content change, for display and rollback.
	Version     int   `json:"version" gorm:"not null;default:1"`
	UpdatedByID *uint `json:"updated_by_id,omitempty"`

	// Managed marks a config auto-created and owned by a platform resource; its
	// lifecycle follows the owner. Mirrors Secret.
	Managed   bool   `json:"managed" gorm:"not null;default:false"`
	OwnerKind string `json:"owner_kind,omitempty" gorm:"index:idx_config_owner"`
	OwnerID   uint   `json:"owner_id,omitempty" gorm:"index:idx_config_owner"`

	Metadata  Metadata  `json:"metadata,omitempty" gorm:"serializer:json"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Config is a workspace-scoped set of named configuration files mounted into applications as read-only files. It is the file-shaped counterpart to Secret, and its content is always encrypted at rest: config files carry credentials more often than not, and the cost is negligible.

type CronJob

type CronJob struct {
	ID            uint   `json:"id" gorm:"primaryKey"`
	WorkspaceID   uint   `json:"workspace_id" gorm:"index;not null"`
	ApplicationID uint   `json:"application_id" gorm:"index;not null"`
	Name          string `json:"name" gorm:"not null"`
	Schedule      string `json:"schedule" gorm:"not null"` // cron expression (UTC)
	// AppName is the owning application's name (transient; populated on read).
	AppName string `json:"app_name,omitempty" gorm:"-"`

	Command     []string `json:"command" gorm:"serializer:json"`
	Entrypoint  []string `json:"entrypoint,omitempty" gorm:"serializer:json"`
	TimeoutSecs int      `json:"timeout_secs" gorm:"not null;default:0"`
	// Image optionally overrides the app's active-release image for spawned jobs
	// (blank = run the app's current image). RegistryID authenticates its pull.
	Image      string `json:"image,omitempty"`
	RegistryID *uint  `json:"registry_id,omitempty"`
	// RunAsUser pins spawned runs to an account (blank = inherit the app's).
	RunAsUser string `json:"run_as_user,omitempty"`

	Enabled           bool   `json:"enabled" gorm:"not null;default:true"`
	ConcurrencyPolicy string `json:"concurrency_policy" gorm:"not null;default:allow"`
	HistoryLimit      int    `json:"history_limit" gorm:"not null;default:0"` // keep last N spawned jobs (0 = default)

	LastRunAt *time.Time `json:"last_run_at"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

CronJob is a schedule that spawns Jobs on a cron expression — the command it carries is the template each spawned Job is created from. Schedules are evaluated in UTC; missed ticks (control plane down) are not backfilled.

type CustomRole

type CustomRole struct {
	ID          uint          `json:"id" gorm:"primaryKey"`
	WorkspaceID *uint         `json:"workspace_id" gorm:"index"`
	Name        string        `json:"name" gorm:"not null"`
	BaseRole    WorkspaceRole `json:"base_role" gorm:"not null"`
	Permissions []string      `json:"permissions" gorm:"serializer:json"`
	CreatedAt   time.Time     `json:"created_at"`
	UpdatedAt   time.Time     `json:"updated_at"`
}

CustomRole is an admin-defined permission set assigned to workspace members (Enterprise, gated on custom_roles for writes). BaseRole gives a rank so the legacy RequireRole still resolves; Permissions drives RequirePermission. The table is empty in Community.

func (*CustomRole) PermissionSet

func (r *CustomRole) PermissionSet() map[Permission]bool

PermissionSet returns the role's permissions as a lookup set.

type DBEngine

type DBEngine string

DBEngine is a supported managed-database engine.

const (
	DBEnginePostgres DBEngine = "postgres"
	DBEngineMySQL    DBEngine = "mysql"
	DBEngineMariaDB  DBEngine = "mariadb"
	DBEngineRedis    DBEngine = "redis"
	DBEngineMongoDB  DBEngine = "mongodb"
	// DBEngineLibSQL is a single-database libSQL (sqld) server. Unlike the SQL
	// engines it hosts exactly one database (no user-managed logical databases),
	// has no CLI client (clients speak HTTP/Hrana), and authenticates with a JWT.
	DBEngineLibSQL DBEngine = "libsql"
)

type DBStatus

type DBStatus string

DBStatus is the lifecycle state of a managed database.

const (
	DBStatusProvisioning DBStatus = "provisioning"
	DBStatusRunning      DBStatus = "running"
	DBStatusStopped      DBStatus = "stopped"
	DBStatusFailed       DBStatus = "failed"
	// DBStatusUpgrading marks an instance whose engine version is being upgraded.
	// Lifecycle actions (start/stop/restart/delete) are refused while in this
	// state; the transient Upgrade* fields carry live progress.
	DBStatusUpgrading DBStatus = "upgrading"
)

type DNSProvider

type DNSProvider struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_dnsprov_workspace_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace.
	Name string `json:"name" gorm:"index:idx_dnsprov_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	Type        string `json:"type" gorm:"not null"` // cloudflare | route53 | digitalocean

	// CredentialsEnc is crypto.Encrypt(JSON-of-credentials); write-only — never
	// serialized to clients (json:"-").
	CredentialsEnc string `json:"-" gorm:"type:text"`

	// Status / LastError record the last connection test or reconcile result.
	Status    string `json:"status" gorm:"not null;default:ok"` // ok | error
	LastError string `json:"last_error,omitempty"`

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

DNSProvider is a workspace's connection to a DNS host. Credentials are an opaque JSON blob whose shape depends on Type (Cloudflare token; Route 53 key/secret/region; DigitalOcean token), encrypted at rest and never returned by the API after create.

type DNSRecord

type DNSRecord struct {
	ID       uint `json:"id" gorm:"primaryKey"`
	DomainID uint `json:"domain_id" gorm:"index:idx_dnsrec_domain_key,unique;not null"`
	// Name+Type form the managed key within a domain (one ledgered record per
	// name+type). Name is a FQDN.
	Name string `json:"name" gorm:"index:idx_dnsrec_domain_key,unique;not null"`
	Type string `json:"type" gorm:"index:idx_dnsrec_domain_key,unique;not null"` // TXT | A | AAAA | CNAME

	Value   string `json:"value"`
	Purpose string `json:"purpose" gorm:"not null"` // verification | app-address
	// AppID is set for app-address records so they are cleaned up when the app /
	// route is removed.
	AppID *uint `json:"app_id,omitempty" gorm:"index"`

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

DNSRecord is the ledger of records Miabi created through a connected provider, so reconcile and cleanup only ever touch records Miabi owns. A record at a managed name that is not in this ledger is treated as a conflict and never overwritten.

type Database

type Database struct {
	UIDModel
	ID            uint     `json:"id" gorm:"primaryKey"`
	WorkspaceID   uint     `json:"workspace_id" gorm:"index;not null"`
	InstanceID    uint     `json:"instance_id" gorm:"index:idx_db_instance_name,unique;not null"`
	Name          string   `json:"name" gorm:"index:idx_db_instance_name,unique;not null"` // db name on the server
	Username      string   `json:"username" gorm:"not null"`
	PasswordEnc   string   `json:"-" gorm:"column:password_enc"` // encrypted
	Status        DBStatus `json:"status" gorm:"not null;default:provisioning"`
	ApplicationID *uint    `json:"application_id,omitempty" gorm:"index"` // optional owner
	// Application declares the FK so deleting the owning app detaches this
	// database (ON DELETE SET NULL) instead of dangling. Not serialized.
	Application *Application `json:"-" gorm:"foreignKey:ApplicationID;constraint:OnDelete:SET NULL"`
	// EnvPrefix namespaces the connection env vars injected into the owning app
	// (e.g. "ANALYTICS" -> ANALYTICS_DATABASE_URL); empty = unprefixed
	// (DATABASE_URL, DB_*). Lets one app hold several databases without clobbering.
	EnvPrefix string `json:"env_prefix,omitempty"`
	// SizeBytes is the database's on-disk size, refreshed by a sync.
	SizeBytes    int64      `json:"size_bytes"`
	SizeSyncedAt *time.Time `json:"size_synced_at"`
	// Metadata holds free-form labels; "miabi.io/" keys are platform-managed.
	Metadata  Metadata  `json:"metadata,omitempty" gorm:"serializer:json"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Database is a logical database hosted on a DatabaseInstance, with its own dedicated user (privileges scoped to this database). The password is encrypted at rest. Optionally owned by an application.

type DatabaseBackupSet added in v1.9.6

type DatabaseBackupSet struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index;not null"`
	InstanceID  uint `json:"instance_id" gorm:"index;not null"`

	// Ref is the stable, human-quotable name of this recovery point:
	// "mbdb_<instance>_<UTC stamp>". Unique and never reused.
	Ref     string       `json:"ref" gorm:"uniqueIndex;not null"`
	Trigger string       `json:"trigger"` // manual | scheduled
	Status  BackupStatus `json:"status" gorm:"not null;default:pending"`

	// Engine and Version describe what the set was taken from. Recorded on the set
	// as well as its items because a restore preflight asks the question once.
	Engine  DBEngine `json:"engine"`
	Version string   `json:"version,omitempty"`
	// Encrypted reports that the artifacts are GPG-encrypted, so the passphrase is
	// needed to restore. False on a set with no items.
	Encrypted bool `json:"encrypted" gorm:"not null;default:false"`
	// Envelope seals this set's random data key under the workspace backup
	// passphrase (see internal/dbenvelope). The artifacts are encrypted with that
	// key rather than the passphrase itself, so rotating the passphrase re-seals a
	// few hundred bytes instead of stranding every set behind the secret it was
	// taken with. Never serialized: it is ciphertext, but publishing it would hand
	// out the thing an offline attack targets.
	Envelope string `json:"-" gorm:"type:text"`

	Destination string `json:"destination"` // local | s3
	S3Bucket    string `json:"s3_bucket,omitempty"`
	S3Path      string `json:"s3_path,omitempty"`
	SizeBytes   int64  `json:"size_bytes"`

	// Error carries why the set did not complete — either its own failure or the
	// first item's.
	Error string `json:"error,omitempty" gorm:"type:text"`

	StartedAt  *time.Time `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at"`
	CreatedAt  time.Time  `json:"created_at"`

	// Verification. An untested backup is the most common reason a recovery fails,
	// so the history says when a set was last checked and not only when it was
	// taken. An empty VerifyStatus means never checked.
	VerifiedAt   *time.Time `json:"verified_at,omitempty"`
	VerifyStatus string     `json:"verify_status,omitempty"` // ok | failed
	VerifyError  string     `json:"verify_error,omitempty" gorm:"type:text"`

	// Items are this recovery point's per-database backups. CASCADE because they
	// have no meaning without it: an artifact whose set is gone cannot be restored
	// as part of one, and leaving it behind shows half a recovery point in the
	// history.
	Items []Backup `json:"items,omitempty" gorm:"foreignKey:SetID;constraint:OnDelete:CASCADE"`
}

DatabaseBackupSet groups the per-database backups taken from one instance in a single run. Without it, backing up an instance's eight databases produces eight unrelated dumps taken at eight different instants: nothing to restore as a unit and nothing to name when someone asks for "last night".

Modelled on PlatformBackupSet, including its central rule — an item failing fails the set, because a partial recovery point is not a recovery point.

func (*DatabaseBackupSet) HasPinnedItem added in v1.9.6

func (s *DatabaseBackupSet) HasPinnedItem() bool

HasPinnedItem reports whether any member is pinned, which exempts the whole set from retention: pruning a set around a pinned member would leave exactly the half-recovery-point the set exists to prevent.

type DatabaseBackupSetSchedule added in v1.9.6

type DatabaseBackupSetSchedule struct {
	ID          uint   `json:"id" gorm:"primaryKey"`
	WorkspaceID uint   `json:"workspace_id" gorm:"index;not null"`
	InstanceID  uint   `json:"instance_id" gorm:"index;not null"`
	Cron        string `json:"cron" gorm:"not null"`
	Enabled     bool   `json:"enabled" gorm:"not null;default:true"`

	// Retention, applied after each run. 0 = unlimited. MaxSets counts recovery
	// points, not the backups inside them.
	MaxSets       int `json:"max_sets" gorm:"not null;default:0"`
	RetentionDays int `json:"retention_days" gorm:"not null;default:0"`

	// Concurrency caps how many databases are dumped at once, as for a manual run.
	// 0 uses the conservative service default.
	Concurrency int `json:"concurrency" gorm:"not null;default:0"`

	LastRunAt *time.Time `json:"last_run_at"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

DatabaseBackupSetSchedule runs a recovery point across an instance on a cron, then applies retention to what it produced.

Deliberately separate from BackupSchedule rather than a nullable InstanceID on it: that model is keyed to a required DatabaseID, its retention counts individual backups rather than sets, and it still carries the per-schedule S3 fields that are no longer used. Widening it would weaken a constraint every existing row depends on.

type DatabaseInstance

type DatabaseInstance struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_dbinst_workspace_name,unique;not null"`
	// Name is the unique, URL/CLI/docker handle (lowercase [a-z0-9-]) scoped to the
	// workspace.
	Name string `json:"name" gorm:"index:idx_dbinst_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI.
	DisplayName string   `json:"display_name"`
	Engine      DBEngine `json:"engine" gorm:"not null"`
	Version     string   `json:"version" gorm:"not null"`
	Status      DBStatus `json:"status" gorm:"not null;default:provisioning"`
	// ServerID is the node this instance runs on (0 = local control-plane node).
	ServerID  uint `json:"server_id" gorm:"index;not null;default:0"`
	ClusterID uint `json:"cluster_id" gorm:"index;not null;default:0"`
	// ServerName is the display name of the node (transient; populated on read so
	// the UI can show where the instance lives). Empty if the node is unknown.
	ServerName  string `json:"server_name,omitempty" gorm:"-"`
	ContainerID string `json:"container_id,omitempty"`
	// Image is the resolved server image ref (repo:tag), pinned at provision time
	// from the deployment-config catalog. Empty on legacy rows (falls back to the
	// engine default).
	Image      string `json:"image,omitempty"`
	VolumeName string `json:"volume_name,omitempty"`
	// VolumeEngineCreatedAt is the creation timestamp Docker reported for the data volume. A timestamp that
	// moved means the volume was deleted and recreated, so the instance's data is gone even though the row
	// and the volume name are intact.
	VolumeEngineCreatedAt string `json:"volume_engine_created_at,omitempty"`
	// VolumeSizeBytes is the declared capacity of the instance's data volume in
	// bytes (0 = unspecified/unlimited), distinct from the measured SizeBytes
	// below. Recorded at provision time for quota accounting.
	VolumeSizeBytes int64 `json:"volume_size_bytes" gorm:"not null;default:0"`
	// MemoryBytes and NanoCPUs are the container's limits (0 = unlimited). The engine is tuned to the memory
	// limit, and both count against the plan's database budget.
	MemoryBytes int64 `json:"memory_bytes" gorm:"not null;default:0"`
	NanoCPUs    int64 `json:"nano_cpus" gorm:"not null;default:0"`
	// SizeClass names the database size the limits came from (Enterprise); empty for limits set by hand. A label
	// only: editing the size later does not change the instance.
	SizeClass string `json:"size_class,omitempty"`
	// MountPath is the in-container data directory the volume is mounted at
	// (transient; populated on read from the engine spec).
	MountPath string `json:"mount_path,omitempty" gorm:"-"`
	Host      string `json:"host"` // in-network DNS alias
	Port      int    `json:"port"`
	// NetworkName is the Docker network the instance joins — the workspace's default network,
	// shared with its applications so they reach the database by alias. The gateway network is
	// reserved for routed apps. Empty on legacy rows, which fall back to gateway.
	NetworkName string `json:"network_name,omitempty"`
	// Admin (superuser/root) credentials for the server. For Redis this is the
	// requirepass password (AdminUser empty).
	AdminUser        string `json:"admin_user"`
	AdminPasswordEnc string `json:"-" gorm:"column:admin_password_enc"` // encrypted
	// JWTPrivateKeyEnc is the encrypted Ed25519 key used to mint client auth tokens for a libSQL
	// instance; sqld starts with the matching public key (SQLD_AUTH_JWT_KEY), derived from it at
	// bring-up. Empty for every other engine.
	JWTPrivateKeyEnc string `json:"-" gorm:"column:jwt_private_key_enc"` // encrypted

	// SizeBytes is the instance's on-disk size (sum of logical DBs for SQL, used
	// memory for Redis), refreshed by a sync. SizeSyncedAt is when it was last
	// computed.
	SizeBytes    int64      `json:"size_bytes"`
	SizeSyncedAt *time.Time `json:"size_synced_at"`

	// Metadata holds free-form labels; "miabi.io/" keys are platform-managed.
	Metadata Metadata `json:"metadata,omitempty" gorm:"serializer:json"`
	// Annotations holds free-form, non-identifying descriptive metadata (the
	// manifest's metadata.annotations); no reserved keys. Persisted as JSON.
	Annotations Metadata  `json:"annotations,omitempty" gorm:"serializer:json"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`

	// Upgrade carries live progress for a version upgrade, persisted as JSON so it is visible
	// across the API server and the worker running the job and survives a restart. Nil when idle;
	// on failure it lingers with Phase="failed" until the next attempt clears it.
	Upgrade *UpgradeProgress `json:"upgrade,omitempty" gorm:"serializer:json"`

	Databases []Database `json:"databases,omitempty" gorm:"foreignKey:InstanceID"`
	// Networks are the Docker networks the instance's container joins. The
	// workspace's default network is always attached (it carries the alias apps
	// reach the instance by); the user may attach additional custom networks.
	Networks []Network `json:"networks,omitempty" gorm:"many2many:database_instance_networks;"`
}

DatabaseInstance is a workspace-owned database server running as a container. One instance hosts one or more logical Databases (SQL engines), so small deployments share a server instead of one container per database. Admin credentials are encrypted at rest.

func (*DatabaseInstance) BeforeCreate added in v1.10.0

func (i *DatabaseInstance) BeforeCreate(tx *gorm.DB) error

func (*DatabaseInstance) NetworkNames

func (i *DatabaseInstance) NetworkNames(fallback string) []string

NetworkNames returns every Docker network the instance joins: the pinned primary first, then the rest. Helper jobs (DDL, size probes, backup, restore) must join the full set or risk landing on a network the instance is not on. De-duplicated and never empty.

func (*DatabaseInstance) SupportsLogicalDatabases

func (i *DatabaseInstance) SupportsLogicalDatabases() bool

SupportsLogicalDatabases reports whether the instance's engine can host named per-app databases with their own users.

func (*DatabaseInstance) SwarmScoped added in v1.10.0

func (i *DatabaseInstance) SwarmScoped(name string) bool

SwarmScoped reports whether name is one of the instance's overlay networks.

type DatabaseSize added in v1.10.0

type DatabaseSize struct {
	ID uint `json:"id" gorm:"primaryKey"`
	// Name is the handle manifests and the API use. Fixed once created, since instances carry it as a label.
	Name        string    `json:"name" gorm:"uniqueIndex;not null"`
	DisplayName string    `json:"display_name"`
	Description string    `json:"description"`
	MemoryBytes int64     `json:"memory_bytes" gorm:"not null"`
	NanoCPUs    int64     `json:"nano_cpus" gorm:"not null"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

DatabaseSize is a named CPU and memory limit a database instance can be given, like a cloud instance class (Enterprise). Editing one sizes only the instances given it afterwards; those already on it keep their limits.

type DeployStrategy

type DeployStrategy string

DeployStrategy is how a new release replaces the running one.

const (
	// DeployRecreate stops the current container before starting the new one
	// (brief downtime; use when two versions cannot run at once).
	DeployRecreate DeployStrategy = "recreate"
	// DeployRolling starts the new container, waits for health, then retires the
	// old one (zero-downtime for a single replica). Default.
	DeployRolling DeployStrategy = "rolling"
	// DeployCanary runs the new release alongside the stable one and shifts
	// weighted traffic to it progressively (platform-driven).
	DeployCanary DeployStrategy = "canary"
)

func EffectiveDeployStrategy added in v1.9.3

func EffectiveDeployStrategy(app *Application, requested DeployStrategy) DeployStrategy

EffectiveDeployStrategy resolves the strategy one deploy runs with: an explicit request wins, else the app's configured default, else rolling.

It lives on the model because every path that creates a Deployment has to apply the same rule, and they do not share a service — a pipeline deploy is built in the worker, a manual one in the application service. When only one of them knew the rule, an app set to canary deployed rolling from CI and nobody could see why.

type Deployment

type Deployment struct {
	ID uint `json:"id" gorm:"primaryKey"`
	// Number is the per-application sequential deployment number, independent of the global ID
	// and mirroring Release.Version. Assigned in BeforeCreate; the composite unique index keeps
	// it gap-free per app and prevents duplicates.
	Number        int              `json:"number" gorm:"index:idx_deploy_app_number,unique;not null;default:0"`
	ApplicationID uint             `json:"application_id" gorm:"index:idx_deploy_app_number,unique;index;not null"`
	Status        DeploymentStatus `json:"status" gorm:"not null;default:pending"`
	Image         string           `json:"image"`
	Trigger       string           `json:"trigger"`                                  // manual | rollback | auto | pipeline | reconcile
	Strategy      DeployStrategy   `json:"strategy" gorm:"not null;default:rolling"` // rollout method for this deploy
	Commit        string           `json:"commit,omitempty"`
	ImageID       *uint            `json:"image_id,omitempty"`
	RegistryID    *uint            `json:"registry_id,omitempty"`
	NoCache       bool             `json:"no_cache,omitempty" gorm:"not null;default:false"`
	RunnerID      *uint            `json:"runner_id,omitempty"`
	ContainerID   string           `json:"container_id,omitempty"`
	Logs          string           `json:"logs,omitempty" gorm:"type:text"`
	LogRef        string           `json:"log_ref,omitempty"`
	LogBytes      int64            `json:"log_bytes,omitempty"`
	LogLines      int              `json:"log_lines,omitempty"`
	LogTruncated  bool             `json:"log_truncated,omitempty"`
	Error         string           `json:"error,omitempty" gorm:"type:text"`
	StartedAt     *time.Time       `json:"started_at"`
	FinishedAt    *time.Time       `json:"finished_at"`
	CreatedAt     time.Time        `json:"created_at"`
	Current       bool             `json:"current" gorm:"-"`
}

Deployment is a single attempt to deploy an application.

func (*Deployment) BeforeCreate

func (d *Deployment) BeforeCreate(tx *gorm.DB) error

type DeploymentStatus

type DeploymentStatus string

DeploymentStatus is the state of a single deploy attempt.

const (
	DeploymentPending   DeploymentStatus = "pending"
	DeploymentBuilding  DeploymentStatus = "building"
	DeploymentDeploying DeploymentStatus = "deploying"
	DeploymentCanary    DeploymentStatus = "canary"
	DeploymentSucceeded DeploymentStatus = "succeeded"
	DeploymentFailed    DeploymentStatus = "failed"
)

func (DeploymentStatus) IsTerminal

func (s DeploymentStatus) IsTerminal() bool

IsTerminal reports whether the deployment has reached a final state.

type DeviceCatalog added in v1.9.6

type DeviceCatalog struct {
	Path  string         `json:"path"`
	Exact bool           `json:"exact"`
	Tier  CapabilityTier `json:"tier"`
	Help  string         `json:"help"`
}

DeviceCatalog describes an exposable device, for the console's picker.

func Devices added in v1.9.6

func Devices() []DeviceCatalog

Devices returns the device allow-list for the API.

type Domain

type Domain struct {
	ID          uint   `json:"id" gorm:"primaryKey"`
	WorkspaceID uint   `json:"workspace_id" gorm:"index:idx_domain_workspace_name,unique;not null"`
	Name        string `json:"name" gorm:"index:idx_domain_workspace_name,unique;not null"` // e.g. example.com

	// TLSMode is the default certificate policy for routes under this domain.
	TLSMode DomainTLSMode `json:"tls_mode" gorm:"not null;default:acme"`
	// Wildcard marks the domain as covering *.name as well as name.
	Wildcard bool `json:"wildcard" gorm:"not null;default:false"`

	// Verified records DNS-proven ownership. VerificationToken is published by the
	// user as a TXT record; it is not a secret (it is meant to be public).
	Verified          bool       `json:"verified" gorm:"not null;default:false"`
	VerifiedAt        *time.Time `json:"verified_at,omitempty"`
	VerificationToken string     `json:"verification_token" gorm:"not null"`
	// VerifiedVia records how ownership was established
	VerifiedVia VerifiedVia `json:"verified_via" gorm:"not null;default:dns"`

	// VerificationCheckedAt records the last ownership check (successful or not) and
	// VerificationError the last failure reason. Together they give the UI a verification history
	// and let the drift cron count consecutive misses before un-verifying a domain.
	VerificationCheckedAt *time.Time `json:"verification_checked_at,omitempty"`
	VerificationError     string     `json:"verification_error,omitempty"`
	// VerificationMisses counts consecutive failed re-verifications of an
	// already-verified domain; the drift cron flips Verified off once it crosses a
	// threshold, absorbing transient DNS blips.
	VerificationMisses int `json:"-" gorm:"not null;default:0"`

	// Banned blocks a domain platform-wide: a banned domain is never served by the
	// gateway (its routes are forced offline) and cannot be verified, regardless of
	// ownership or workspace privilege. Set by a platform admin (e.g. for abuse).
	Banned    bool       `json:"banned" gorm:"not null;default:false"`
	BannedAt  *time.Time `json:"banned_at,omitempty"`
	BanReason string     `json:"ban_reason,omitempty"`

	// DNSProviderID optionally links the domain to a connected DNS provider so
	// Miabi automates the ownership TXT (and, later, app A/AAAA) records. nil =
	// manual: the user adds DNS records by hand (today's copy-paste flow).
	DNSProviderID *uint        `json:"dns_provider_id,omitempty" gorm:"index"`
	DNSProvider   *DNSProvider `json:"-" gorm:"foreignKey:DNSProviderID;constraint:OnDelete:SET NULL"`

	// ServingUnverified marks a domain the gateway serves despite failing the ownership
	// gate
	ServingUnverified bool `json:"serving_unverified,omitempty" gorm:"-"`

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

Domain is a hostname (or zone) a workspace owns, tracking DNS-verified ownership and the default TLS policy; routes bind hostnames resolving under a verified domain. Distinct from the declarative Route kind, which is an HTTP routing rule.

func (*Domain) ChallengeHost

func (d *Domain) ChallengeHost() string

ChallengeHost is the DNS name where the ownership TXT record must be added.

func (*Domain) ChallengeValue

func (d *Domain) ChallengeValue() string

ChallengeValue is the expected TXT record value proving ownership.

func (*Domain) Status

func (d *Domain) Status() DomainStatus

Status derives the domain's presentational state for the UI. A ban takes precedence over verification, since it overrides serving entirely.

type DomainStatus

type DomainStatus string

DomainStatus is a presentational verification state derived from the domain's verification fields (not stored): "verified", "failed" (a check ran and did not prove ownership), or "pending" (no successful check yet).

const (
	DomainStatusPending  DomainStatus = "pending"
	DomainStatusVerified DomainStatus = "verified"
	DomainStatusFailed   DomainStatus = "failed"
	DomainStatusBanned   DomainStatus = "banned"
)

type DomainTLSMode

type DomainTLSMode string

DomainTLSMode is the default certificate policy for routes served under a domain.

const (
	// DomainTLSACME serves certificates from Goma's ACME (Let's Encrypt) issuer.
	DomainTLSACME DomainTLSMode = "acme"
	// DomainTLSCustom expects a user-supplied certificate.
	DomainTLSCustom DomainTLSMode = "custom"
)

type EmailVerificationToken added in v1.9.6

type EmailVerificationToken struct {
	ID        uint       `json:"id" gorm:"primaryKey"`
	UserID    uint       `json:"user_id" gorm:"index;not null"`
	TokenHash string     `json:"-" gorm:"uniqueIndex;not null"`
	ExpiresAt time.Time  `json:"expires_at" gorm:"not null"`
	UsedAt    *time.Time `json:"used_at"`
	CreatedAt time.Time  `json:"created_at"`
}

EmailVerificationToken is a single-use, expiring proof that someone can read the address they registered. Modelled on PasswordResetToken: same shape, same single-use semantics, separate table so revoking one never affects the other.

type Environment

type Environment struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_env_ws_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace (e.g. "prod").
	Name string `json:"name" gorm:"index:idx_env_ws_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	Description string `json:"description,omitempty"`
	// Rank orders environments for promotion flow (lower promotes into higher).
	Rank int `json:"rank" gorm:"not null;default:0"`
	// RequiredApprovals gates promotion into this environment (0 = no gate).
	RequiredApprovals int `json:"required_approvals" gorm:"not null;default:0"`
	// GitSourceID optionally binds the environment to a GitOps source/folder.
	GitSourceID *uint `json:"git_source_id,omitempty" gorm:"index"`

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

Environment is a promotion stage within a workspace (dev → staging → prod). A Release is promoted by updating the target environment's desired state — a Git commit (GitOps) or an API write — so promotion is auditable and reconciled.

type EventSubjectType added in v1.9.5

type EventSubjectType string

EventSubjectType names the kind of resource a timeline event is about. An event carries exactly one subject; the matching id column holds it and the other stays 0.

const (
	SubjectApp      EventSubjectType = "app"
	SubjectDatabase EventSubjectType = "database"
)

type GPUDevice added in v1.2.0

type GPUDevice struct {
	ID       uint `json:"id" gorm:"primaryKey"`
	ServerID uint `json:"server_id" gorm:"index;not null"` // the node it lives on

	// UUID is the stable identity reported by the node agent (nvidia-smi -q -x),
	// e.g. "GPU-3f2c...". It is the join key across re-inventories.
	UUID     string    `json:"uuid" gorm:"uniqueIndex;not null"`
	Index    int       `json:"index"` // host-local device index at last inventory (informational)
	Vendor   GPUVendor `json:"vendor" gorm:"not null;default:nvidia"`
	Model    string    `json:"model"`     // "NVIDIA A100-SXM4-40GB"
	MemoryMB int       `json:"memory_mb"` // total framebuffer memory

	// Admin policy. A device is not offered to any workload until Enabled — a
	// newly discovered card always arrives disabled (fail closed).
	Enabled bool `json:"enabled" gorm:"not null;default:false"`
	// Shared: many apps may request this device concurrently (inference, dev).
	// Dedicated (false): reserved for one app at a time (training). Fleet-wide
	// exclusivity enforcement for dedicated cards lands in a later phase.
	Shared bool `json:"shared" gorm:"not null;default:true"`

	// LastSeenAt is stamped on every inventory scan that observes the device. A device missing
	// from a scan is kept, not deleted, so history and an app's GPUKind reference survive a
	// transient probe failure; staleness is derived from an old LastSeenAt.
	LastSeenAt *time.Time `json:"last_seen_at"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`
}

GPUDevice is one physical GPU discovered on a node's Docker host, owned by a Server and keyed by the stable nvidia-smi UUID — never the host-local index, which changes across reboots. Each is individually enabled/shared and is the unit an app is scheduled onto.

type GPUVendor added in v1.2.0

type GPUVendor string

GPUVendor is the vendor of a physical GPU. Only "nvidia" is supported in v1; "amd" is reserved for a later ROCm phase.

const (
	GPUVendorNvidia GPUVendor = "nvidia"
	GPUVendorAMD    GPUVendor = "amd" // reserved (ROCm), not yet supported
)

type GatewayUpdateProgress

type GatewayUpdateProgress struct {
	FromImage string `json:"from_image"`
	ToImage   string `json:"to_image"`
	// Phase: queued | pulling | testing | observing | promoting | verifying |
	// done | failed.
	Phase string `json:"phase"`
	Error string `json:"error,omitempty"`
}

GatewayUpdateProgress is the live state of a safe edge-gateway update: the new image runs as a throwaway test container with the same config and volumes, is observed for a grace period, then promoted to replace the live gateway. Mirrors UpgradeProgress.

type GitAuthType

type GitAuthType string

GitAuthType is how an application authenticates to a Git repository.

const (
	// GitAuthPublic is an anonymous (public) repository — no credentials.
	GitAuthPublic GitAuthType = "public"
	// GitAuthToken uses HTTPS basic auth (username + personal access token).
	GitAuthToken GitAuthType = "token"
	// GitAuthSSH uses an SSH private key against an ssh:// or git@ URL.
	GitAuthSSH GitAuthType = "ssh"
)

type GitConnectionStatus added in v1.9.0

type GitConnectionStatus string

GitConnectionStatus is the result of the last reachability check.

const (
	// GitConnectionUnknown is a credential that has never been checked, or whose
	// URL/credential changed since the last check.
	GitConnectionUnknown GitConnectionStatus = "unknown"
	// GitConnectionOK means the remote answered and the credential authenticated.
	GitConnectionOK GitConnectionStatus = "ok"
	// GitConnectionFailed means the last check could not reach or authenticate to
	// the remote; ConnectionError says why.
	GitConnectionFailed GitConnectionStatus = "failed"
)

type GitRepository

type GitRepository struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_gitrepo_workspace_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace.
	Name string `json:"name" gorm:"index:idx_gitrepo_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string      `json:"display_name"`
	URL         string      `json:"url" gorm:"not null"`
	AuthType    GitAuthType `json:"auth_type" gorm:"not null;default:token"`
	// Username for HTTPS basic auth. Empty defaults to a provider-friendly value
	// ("x-access-token") at clone time.
	Username string `json:"username"`
	// Secret holds the access token (token auth) or SSH private key (ssh auth),
	// encrypted at rest. Empty when the credential points at the vault instead
	// (see SecretRef).
	Secret string `json:"-" gorm:"not null"`
	// SecretRef names a workspace Secret holding the token instead of storing a copy here. The
	// value is read from the vault at every clone, so rotating that secret rotates this
	// credential. Mutually exclusive with Secret; a name, so the API returns it.
	SecretRef string `json:"secret_ref,omitempty"`

	// Connection state from the last reachability check: a `git ls-remote` against
	// the URL with this credential. Persisted so the list can show whether a
	// credential actually works without re-probing every remote on every page load
	// — which would be slow, and would hammer the provider from a read.
	//
	// It is a point-in-time observation, not a guarantee: a token can be revoked a
	// minute after a successful check, so ConnectionCheckedAt is shown alongside
	// the status rather than the status standing on its own.
	ConnectionStatus GitConnectionStatus `json:"connection_status,omitempty" gorm:"not null;default:unknown"`
	// ConnectionError is the failure reason from the last check, empty when it
	// succeeded. Surfaced verbatim so "authentication required" and "repository not
	// found" stay distinguishable — they need different fixes.
	ConnectionError     string     `json:"connection_error,omitempty"`
	ConnectionCheckedAt *time.Time `json:"connection_checked_at,omitempty"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// HasSecret is a transient flag for responses (never persisted): true when the
	// credential can authenticate, whether from its own stored secret or a vault
	// reference.
	HasSecret bool `json:"has_secret" gorm:"-"`
}

GitRepository is a stored Git credential used to clone private repositories at build time. The Secret (token or SSH private key) is encrypted at rest and never serialized.

type GitSource

type GitSource struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_gitsource_ws_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace.
	Name string `json:"name" gorm:"index:idx_gitsource_ws_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`

	RepoURL string `json:"repo_url" gorm:"not null"`
	Ref     string `json:"ref" gorm:"not null;default:main"` // branch, tag or commit
	Path    string `json:"path" gorm:"not null;default:."`   // manifest subdirectory

	// GitRepositoryID optionally references stored credentials (token/SSH) for a
	// private repository. nil means the repo is public.
	GitRepositoryID *uint `json:"git_repository_id,omitempty" gorm:"index"`

	SyncPolicy GitSyncPolicy `json:"sync_policy" gorm:"not null;default:manual"`
	// Prune deletes managed resources that disappear from Git (opt-in for safety).
	Prune bool `json:"prune" gorm:"not null;default:false"`
	// SelfHeal re-applies when the live state drifts from Git.
	SelfHeal bool `json:"self_heal" gorm:"not null;default:false"`
	// AllowEmpty permits an empty manifest set to prune ALL managed resources (intentional
	// teardown). Off by default, so a wrong path or a wiped repo cannot tear down a deployment.
	// A missing path is always an error. Only meaningful together with Prune.
	AllowEmpty bool `json:"allow_empty" gorm:"not null;default:false"`

	// WebhookSecret authenticates inbound provider push webhooks. Never serialized.
	WebhookSecret string `json:"-" gorm:"not null"`

	Status  GitSourceStatus `json:"status" gorm:"not null;default:unknown"`
	Message string          `json:"message,omitempty" gorm:"type:text"`

	LastSyncedCommit  string     `json:"last_synced_commit,omitempty"`
	LastSyncedAuthor  string     `json:"last_synced_author,omitempty"`
	LastSyncedSubject string     `json:"last_synced_subject,omitempty"`
	LastSyncedAt      *time.Time `json:"last_synced_at,omitempty"`

	LastCheckedCommit string     `json:"last_checked_commit,omitempty"`
	LastCheckedAt     *time.Time `json:"last_checked_at,omitempty"`

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

GitSource binds a Git path of miabi.io/v1 manifests to a workspace as a continuously-reconciled desired-state source — the GitOps half of the declarative model: Git -> (sync) -> Postgres desired -> (reconciler) -> Docker.

type GitSourceStatus

type GitSourceStatus string

GitSourceStatus is the aggregate sync state of a GitSource.

const (
	GitSourceUnknown     GitSourceStatus = "unknown"
	GitSourceSynced      GitSourceStatus = "synced"
	GitSourceOutOfSync   GitSourceStatus = "out_of_sync"
	GitSourceProgressing GitSourceStatus = "progressing"
	GitSourceError       GitSourceStatus = "error"
)

type GitSyncPolicy

type GitSyncPolicy string

GitSyncPolicy controls when a GitSource reconciles.

const (
	// GitSyncManual reconciles only on an explicit Sync (or webhook) request.
	GitSyncManual GitSyncPolicy = "manual"
	// GitSyncAuto reconciles on the polling sweep and on webhook push.
	GitSyncAuto GitSyncPolicy = "auto"
)

type HealthcheckType

type HealthcheckType string

HealthcheckType is how an application's container health is probed.

const (
	HealthcheckNone    HealthcheckType = "none"    // no healthcheck
	HealthcheckHTTP    HealthcheckType = "http"    // HTTP GET against a path/port
	HealthcheckCommand HealthcheckType = "command" // shell command (CMD-SHELL)
)

type Image

type Image struct {
	ID          uint   `json:"id" gorm:"primaryKey"`
	WorkspaceID uint   `json:"workspace_id" gorm:"index:idx_image_ws_digest,unique;not null"`
	Repository  string `json:"repository" gorm:"not null"`
	Digest      string `json:"digest" gorm:"index:idx_image_ws_digest,unique;not null"` // sha256:…
	Tag         string `json:"tag,omitempty"`
	SizeBytes   int64  `json:"size_bytes"`

	PipelineRunID *uint      `json:"pipeline_run_id,omitempty" gorm:"index"`
	ApplicationID *uint      `json:"application_id,omitempty" gorm:"index"`
	Commit        string     `json:"commit,omitempty"`
	Runner        string     `json:"runner,omitempty"`
	BuiltAt       *time.Time `json:"built_at,omitempty"`

	// SBOM / Signature attach supply-chain metadata. Never serialized.
	SBOM      string `json:"-" gorm:"type:text"`
	Signature string `json:"-" gorm:"type:text"`

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

Image is a built container artifact with provenance. Deploy-by-digest records exactly what ran; the catalog/GC reasons about retention without ever collecting a digest a live deployment or pinned release references.

func (*Image) Ref

func (i *Image) Ref() string

Ref returns the canonical repository@digest pin.

type ImagePullPolicy

type ImagePullPolicy string

ImagePullPolicy decides whether a deploy pulls the image: "always" (default), "if-not-present" reuses a cached image, "never" requires it present (air-gapped). Digest-pinned refs are immutable, so they are never re-pulled when already present.

const (
	PullAlways       ImagePullPolicy = "always"         // always pull (default)
	PullIfNotPresent ImagePullPolicy = "if-not-present" // pull only when the image is absent locally
	PullNever        ImagePullPolicy = "never"          // never pull; fail if the image is absent
)

type InvitationStatus

type InvitationStatus string

InvitationStatus is the lifecycle state of a workspace invitation.

const (
	InvitationStatusPending  InvitationStatus = "pending"
	InvitationStatusAccepted InvitationStatus = "accepted"
	InvitationStatusRevoked  InvitationStatus = "revoked"
)

type Job

type Job struct {
	ID            uint `json:"id" gorm:"primaryKey"`
	WorkspaceID   uint `json:"workspace_id" gorm:"index;not null"`
	ApplicationID uint `json:"application_id" gorm:"index;not null"`
	// ServerID is the node the job ran on (0 = local), copied from the app.
	ServerID  uint `json:"server_id" gorm:"not null;default:0"`
	ClusterID uint `json:"cluster_id" gorm:"index;not null;default:0"`
	// CronJobID links runs spawned by a CronJob to their schedule.
	CronJobID *uint `json:"cronjob_id,omitempty" gorm:"index"`
	// AppName is the owning application's name (transient; populated on read for
	// the workspace-level Jobs view).
	AppName string `json:"app_name,omitempty" gorm:"-"`

	Name       string   `json:"name"`
	Command    []string `json:"command" gorm:"serializer:json"`
	Entrypoint []string `json:"entrypoint,omitempty" gorm:"serializer:json"`
	Image      string   `json:"image"` // resolved image actually run
	// RegistryID authenticates the image pull for a custom image (nil = the app's registry, or
	// anonymous). Pull marks that the image must be fetched first — set for a custom image; the
	// app's release image is already on its node and git-built images are local-only.
	RegistryID *uint `json:"registry_id,omitempty"`
	Pull       bool  `json:"pull"`
	// RunAsUser is the account the run was pinned to, snapshotted from the request or the app so
	// history shows what actually ran. Empty = the image's own user (or the platform UID when the
	// restricted profile applies). See models.NormalizeRunAsUser.
	RunAsUser   string    `json:"run_as_user,omitempty"`
	Status      JobStatus `json:"status" gorm:"not null;default:pending"`
	ExitCode    *int      `json:"exit_code,omitempty"`
	ContainerID string    `json:"container_id,omitempty"`

	Logs         string `json:"logs,omitempty" gorm:"type:text"`
	LogRef       string `json:"log_ref,omitempty"`
	LogBytes     int64  `json:"log_bytes,omitempty"`
	LogLines     int    `json:"log_lines,omitempty"`
	LogTruncated bool   `json:"log_truncated,omitempty"`
	Error        string `json:"error,omitempty" gorm:"type:text"`
	TimeoutSecs  int    `json:"timeout_secs" gorm:"not null;default:0"`

	TriggeredByID *uint  `json:"triggered_by_id,omitempty"`
	Source        string `json:"source" gorm:"not null;default:manual"` // manual | api | scheduled

	StartedAt  *time.Time `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`
}

Job is a one-off command run in an application's runtime context (same image, env, networks, volumes, node and limits). The command is captured for history/audit; secrets are resolved into the container env at run time and never persisted on the row.

func (*Job) BeforeCreate added in v1.10.0

func (j *Job) BeforeCreate(tx *gorm.DB) error

type JobStatus

type JobStatus string

JobStatus is the lifecycle state of a one-off Job run.

const (
	JobPending   JobStatus = "pending"
	JobRunning   JobStatus = "running"
	JobSucceeded JobStatus = "succeeded"
	JobFailed    JobStatus = "failed"
	JobCanceled  JobStatus = "canceled"
)

func (JobStatus) IsTerminal

func (s JobStatus) IsTerminal() bool

IsTerminal reports whether the job has reached a final state.

type LDAPConfig

type LDAPConfig struct {
	ID             uint  `json:"id" gorm:"primaryKey"`
	OrganizationID *uint `json:"organization_id" gorm:"index"`
	// Name is the globally unique handle (slug); DisplayName is the free-text label.
	Name        string `json:"name" gorm:"uniqueIndex;not null"`
	DisplayName string `json:"display_name"`

	Host            string `json:"host" gorm:"not null"`
	Port            int    `json:"port" gorm:"not null;default:389"`
	TLSMode         string `json:"tls_mode" gorm:"not null;default:'starttls'"` // none | starttls | ldaps
	CACertPEM       string `json:"ca_cert_pem" gorm:"type:text"`                // optional private-CA trust
	InsecureSkipTLS bool   `json:"insecure_skip_tls" gorm:"not null;default:false"`
	TimeoutSeconds  int    `json:"timeout_seconds" gorm:"not null;default:10"`

	// Bind — the service account used to search for the user entry before
	// re-binding as the user to verify the password.
	BindDN string `json:"bind_dn"`
	// BindPasswordEnc is the service-account password, encrypted at rest (crypto
	// package). Never serialized; BindPasswordSet exposes only whether it is set.
	BindPasswordEnc string `json:"-" gorm:"type:text"`

	UserBaseDN   string `json:"user_base_dn"`
	UserFilter   string `json:"user_filter"`   // %s = escaped identifier, e.g. (sAMAccountName=%s) or (uid=%s)
	AttrEmail    string `json:"attr_email"`    // mail | userPrincipalName (blank → "mail")
	AttrName     string `json:"attr_name"`     // displayName | cn (blank → "displayName")
	AttrUsername string `json:"attr_username"` // sAMAccountName | uid → User.Username

	// Group resolution (optional; drives access via LDAPGroupMapping).
	GroupBaseDN  string `json:"group_base_dn"`
	GroupFilter  string `json:"group_filter"`  // %s = user DN, e.g. (member=%s); blank → use MemberAttr
	MemberAttr   string `json:"member_attr"`   // memberOf (read from the user entry) — AD default
	NestedGroups bool   `json:"nested_groups"` // AD: expand nested groups (LDAP_MATCHING_RULE_IN_CHAIN)

	Enabled   bool      `json:"enabled" gorm:"not null;default:true"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// Mappings are loaded on demand (not embedded in list responses).
	Mappings []LDAPGroupMapping `json:"mappings,omitempty" gorm:"foreignKey:LDAPConfigID"`

	// BindPasswordSet is a read-only flag for the API (whether a service-account
	// password is stored) so the secret itself is never exposed. Not persisted;
	// populated by the repository on read.
	BindPasswordSet bool `json:"bind_password_set" gorm:"-"`
}

LDAPConfig is an LDAP / Active Directory connection for an organization. Migrated in every build but only read by the enterprise LDAP authenticator and admin handler (gated on sso_ldap); empty in Community. Mirrors SAMLConfig's per-org shape.

type LDAPGroupMapping

type LDAPGroupMapping struct {
	ID           uint `json:"id" gorm:"primaryKey"`
	LDAPConfigID uint `json:"ldap_config_id" gorm:"index;not null"`
	// GroupDN is matched (case-insensitively) against the user's resolved group
	// DNs; a bare CN is also accepted for convenience.
	GroupDN     string `json:"group_dn" gorm:"not null"`
	SystemAdmin bool   `json:"system_admin" gorm:"not null;default:false"`
	// WorkspaceID + WorkspaceRole grant workspace membership (nil = no grant).
	WorkspaceID   *uint         `json:"workspace_id"`
	WorkspaceRole WorkspaceRole `json:"workspace_role"`
	CreatedAt     time.Time     `json:"created_at"`
	UpdatedAt     time.Time     `json:"updated_at"`
}

LDAPGroupMapping maps a directory group to Miabi access, reconciled on every login: SystemAdmin grants the platform-admin role, a WorkspaceID + WorkspaceRole grants membership. A mapping with neither is a no-op, kept for documentation.

type LeaseKind

type LeaseKind string

LeaseKind namespaces a lease's RunID so pipeline runs and deploy builds — two different id spaces — never collide in the shared runner_leases table.

const (
	// LeaseKindPipeline: RunID is a PipelineRun id.
	LeaseKindPipeline LeaseKind = "pipeline"
	// LeaseKindBuild: RunID is a Deployment id (a git-app build dispatched to a
	// runner, outside any pipeline).
	LeaseKindBuild LeaseKind = "build"
)

type License

type License struct {
	ID          uint      `json:"id" gorm:"primaryKey"`
	LicenseID   string    `json:"license_id" gorm:"uniqueIndex;not null"`
	Edition     string    `json:"edition" gorm:"not null"`
	Token       string    `json:"-" gorm:"type:text;not null"` // never serialized to the API
	Customer    string    `json:"customer"`
	NotBefore   time.Time `json:"not_before"`
	NotAfter    time.Time `json:"not_after"`
	GraceDays   int       `json:"grace_days"`
	InstalledBy uint      `json:"installed_by"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

License is the single active commercial license row. The signed Token is the source of truth, re-verified against the embedded public key on every load, so the parsed columns are only a display cache. Migrated in every build but empty and unused in Community.

type Metadata

type Metadata = map[string]string

Metadata is a free-form set of key/value labels on a resource, backing provenance, grouping and the declarative/GitOps features. Keys under MetadataReservedPrefix are platform-managed and protected from user modification. Persisted as JSON.

func DefaultManagedBy

func DefaultManagedBy(m Metadata, value string) Metadata

DefaultManagedBy ensures the managed-by built-in is set, defaulting to value when absent, and returns the (possibly newly created) map. Used at creation so every resource records its origin.

func DefaultOwner

func DefaultOwner(m Metadata, kind string, id uint, name string) Metadata

DefaultOwner sets the owner reference only when one is not already present, so higher-level callers (marketplace, stacks, apply) that record a richer owner win over a creation-path default. Returns the (possibly updated) map.

func MergeUserMetadata

func MergeUserMetadata(current, overlay Metadata) Metadata

MergeUserMetadata applies a user overlay onto current metadata while protecting built-in keys: reserved keys from current are preserved, non-reserved keys are replaced wholesale so users can add or remove their own labels.

func SanitizeUserMetadata

func SanitizeUserMetadata(in Metadata) Metadata

SanitizeUserMetadata returns a copy of in with all reserved (built-in) keys removed, so user-supplied metadata can never set or spoof platform-managed keys. nil in → nil out.

func SetBuiltin

func SetBuiltin(m Metadata, kv ...string) Metadata

SetBuiltin sets one or more reserved (built-in) key/value pairs on m, creating the map if needed, and returns it. Reserved keys are authoritative, so this always wins. Pairs are passed as key, value, key, value, …

func SetOwner

func SetOwner(m Metadata, kind string, id uint, name string) Metadata

SetOwner records the owner reference on m (creating the map if needed) and returns it. id is omitted when 0 and name when empty, so callers can record a partial reference (e.g. kind+id with the name resolved later).

type MetricSample

type MetricSample struct {
	ID            uint      `json:"id" gorm:"primaryKey"`
	ApplicationID uint      `json:"application_id" gorm:"index:idx_metric_app_time;not null"`
	RecordedAt    time.Time `json:"recorded_at" gorm:"index:idx_metric_app_time"`
	CPUPercent    float64   `json:"cpu_percent"`
	MemoryBytes   uint64    `json:"memory_bytes"`
	MemoryPercent float64   `json:"memory_percent"`
	NetRxBytes    uint64    `json:"net_rx_bytes"`
	NetTxBytes    uint64    `json:"net_tx_bytes"`
}

MetricSample is a point-in-time resource sample for an application, captured by the background scraper for short-term history.

type Middleware

type Middleware struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_mw_workspace_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace (Goma middleware name).
	Name string `json:"name" gorm:"index:idx_mw_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string                 `json:"display_name"`
	Type        string                 `json:"type" gorm:"not null"` // Goma middleware kind, e.g. basicAuth, rateLimit
	Paths       []string               `json:"paths,omitempty" gorm:"serializer:json"`
	Rule        map[string]interface{} `json:"rule,omitempty" gorm:"serializer:json"`
	CreatedAt   time.Time              `json:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at"`
}

Middleware is a Goma Gateway middleware owned by a workspace. Routes reference it by Name. Rule holds the type-specific configuration as defined by Goma (mirrors goma-admin's JSON config approach).

type Network

type Network struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_network_workspace_name,unique;not null"`
	// Name is the unique slug handle (lowercase [a-z0-9-]) scoped to the workspace.
	Name string `json:"name" gorm:"index:idx_network_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	DockerName  string `json:"docker_name" gorm:"uniqueIndex;not null"`
	Driver      string `json:"driver" gorm:"not null;default:bridge"`
	Internal    bool   `json:"internal" gorm:"not null;default:false"`
	IsDefault   bool   `json:"is_default" gorm:"not null;default:false"`
	// Imported marks a network that references a pre-existing external Docker
	// network by its own name (DockerName = the existing name; nothing recreated).
	Imported  bool      `json:"imported" gorm:"not null;default:false"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Network is a managed Docker network owned by a workspace. The user-facing Name is unique per workspace; DockerName is the platform-managed, globally unique Docker network name (workspace + short id).

func (*Network) SwarmScoped added in v1.10.0

func (n *Network) SwarmScoped() bool

SwarmScoped reports whether the network is a swarm overlay. A worker cannot see one until a container there attaches, so ensuring it by name on a worker would create a same-named bridge.

type NetworkAllocation

type NetworkAllocation struct {
	ID uint `json:"id" gorm:"primaryKey"`
	// DockerName is the globally-unique Docker network name this subnet is pinned to.
	DockerName string `json:"docker_name" gorm:"uniqueIndex;not null"`
	// Subnet is the allocated CIDR (e.g. 10.42.3.0/24); Gateway is its first host.
	Subnet  string `json:"subnet" gorm:"uniqueIndex;not null"`
	Gateway string `json:"gateway" gorm:"not null"`
	// NodeID is the node the network lives on (0 = local control-plane node). The
	// same subnet may recur across nodes for the same logical network — bridges are
	// node-local — so uniqueness is on DockerName/Subnet, not (Subnet, NodeID).
	NodeID uint `json:"node_id" gorm:"not null;default:0"`
	// Kind labels the allocation (see NetAllocKind*).
	Kind      string    `json:"kind" gorm:"not null;default:workspace"`
	CreatedAt time.Time `json:"created_at"`
}

NetworkAllocation pins one Docker network to a subnet carved from the platform pool (MIABI_NETWORK_POOL_CIDR) — the ledger the allocator consults for non-overlapping subnets. Keyed by DockerName; reserved rows use the sentinel "reserved:<subnet>".

type NodePlacement

type NodePlacement struct {
	// Name is the node's Miabi display name, or a short swarm node id when the node
	// is not (yet) correlated to a Miabi server record.
	Name string `json:"name"`
	// Tasks is the number of the app's running tasks on this node.
	Tasks int `json:"tasks"`
}

NodePlacement is where one slice of a cluster app's replicas runs: a node's display name and how many of the app's running tasks the scheduler placed on it. Transient — built on read from live Swarm task placement.

type Notification added in v1.6.0

type Notification struct {
	ID uint `json:"id" gorm:"primaryKey"`
	// WorkspaceID is 0 for platform-scoped items (announcements), which follow the
	// user into every workspace they open rather than belonging to any one of them.
	UserID         uint          `json:"user_id" gorm:"index:idx_notif_user_alert,priority:1;not null"`
	WorkspaceID    uint          `json:"workspace_id" gorm:"index;not null"`
	AlertID        *uint         `json:"alert_id,omitempty" gorm:"index:idx_notif_user_alert,priority:2"`
	AnnouncementID *uint         `json:"announcement_id,omitempty" gorm:"index"`
	Kind           string        `json:"kind" gorm:"not null;default:alert"` // alert | info | announcement
	Category       AlertCategory `json:"category"`
	Severity       AlertSeverity `json:"severity" gorm:"not null;default:info"`
	Title          string        `json:"title"`
	Body           string        `json:"body"`
	SubjectLink    string        `json:"subject_link,omitempty"`
	ActionText     string        `json:"action_text,omitempty"`

	// Pinned raises the item to an app-wide banner until dismissed. Denormalized
	// from the announcement so the banner is a plain inbox query with no join.
	Pinned bool `json:"pinned" gorm:"not null;default:false"`
	// Dismissal is denormalized from the announcement, for the same reason Pinned
	// is: the banner stays a plain per-user query with no join.
	Dismissal AnnouncementDismissal `json:"dismissal" gorm:"not null;default:once"`
	// ExpiresAt retires the item from the banner without deleting the history.
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	// DismissedAt hides the item from the banner. Distinct from ReadAt: opening the
	// bell reads a notice, deciding you are done with it dismisses it.
	DismissedAt *time.Time `json:"dismissed_at,omitempty"`
	// ReadAt is nil while unread. Read state is per-user.
	ReadAt    *time.Time `json:"read_at,omitempty"`
	CreatedAt time.Time  `json:"created_at" gorm:"index"`
	UpdatedAt time.Time  `json:"updated_at"`
}

Notification is a per-user inbox item — the delivery of an Alert or an Announcement to one member. Alerts are workspace-level and shared; notifications are per-user so read/unread stays clean. It renders the source at delivery time and updates in place rather than spamming the bell.

type NotificationChannel

type NotificationChannel struct {
	ID          uint                    `json:"id" gorm:"primaryKey"`
	WorkspaceID uint                    `json:"workspace_id" gorm:"index;not null"`
	Type        NotificationChannelType `json:"type" gorm:"not null"`
	Name        string                  `json:"name"`
	Config      map[string]string       `json:"config" gorm:"serializer:json"`
	Events      []string                `json:"events" gorm:"serializer:json"`
	Enabled     bool                    `json:"enabled" gorm:"not null;default:true"`

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

NotificationChannel is a workspace-configured outbound channel that pushes a human-readable message when a subscribed event fires. Transport settings live in Config; secret values are encrypted at rest and masked in API responses.

type NotificationChannelType

type NotificationChannelType string

NotificationChannelType identifies a notification transport. Telegram ships first; the model is generic so Slack/Discord/email can follow.

const (
	ChannelTelegram NotificationChannelType = "telegram"
	ChannelSlack    NotificationChannelType = "slack"
	ChannelDiscord  NotificationChannelType = "discord"
)

type OAuthProvider

type OAuthProvider struct {
	ID uint `json:"id" gorm:"primaryKey"`
	// Name is the globally unique handle used in callback routes.
	Name string `json:"name" gorm:"uniqueIndex;not null"`
	// DisplayName is the free-text label shown on login buttons.
	DisplayName string            `json:"display_name"`
	Type        OAuthProviderType `json:"type" gorm:"not null"`

	ClientID        string `json:"-" gorm:"not null"`
	ClientSecretEnc string `json:"-" gorm:"column:client_secret;not null"`

	// OIDC endpoints. For "google" these are derived from the well-known config.
	Issuer      string `json:"issuer"`
	AuthURL     string `json:"auth_url"`
	TokenURL    string `json:"token_url"`
	UserInfoURL string `json:"userinfo_url"`

	Scopes string `json:"scopes" gorm:"default:'openid email profile'"`

	Enabled      bool `json:"enabled" gorm:"default:true;not null"`
	Hidden       bool `json:"hidden" gorm:"default:false;not null"`       // hide from login buttons
	AutoRegister bool `json:"auto_register" gorm:"default:true;not null"` // auto-create users on first login

	// AllowedDomains is a CSV of email domains permitted to sign in / register
	// through this provider. Empty means any domain is allowed.
	AllowedDomains string `json:"allowed_domains"`

	// OrganizationID is the realm this provider belongs to (nullable → default org).
	OrganizationID *uint `json:"organization_id" gorm:"index"`

	// EmailClaim / NameClaim / UsernameClaim map a generic OIDC userinfo claim
	// onto the user's email / display name / handle. Empty falls back to the
	// standard "email" / "name" / "preferred_username".
	EmailClaim string `json:"email_claim"`
	NameClaim  string `json:"name_claim"`
	// UsernameClaim names the claim carrying the handle the user is known by at
	// the provider. Without it Miabi derives one from the email local part, so an
	// account whose directory handle differs from its mailbox gets the wrong one.
	UsernameClaim string `json:"username_claim"`

	// DefaultWorkspaceID + DefaultRole auto-join a newly registered SSO user to a
	// workspace with a role on first login. Nil = no auto-join (user is invited
	// separately).
	DefaultWorkspaceID *uint         `json:"default_workspace_id" gorm:"index"`
	DefaultRole        WorkspaceRole `json:"default_role"`

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

OAuthProvider is a platform-level SSO identity provider. Secrets are stored encrypted at rest (see internal/services/crypto) and never serialized.

type OAuthProviderType

type OAuthProviderType string

OAuthProviderType is the kind of identity provider.

const (
	OAuthProviderGoogle OAuthProviderType = "google" // Google OAuth 2.0 (well-known discovery)
	OAuthProviderOIDC   OAuthProviderType = "oidc"   // generic OpenID Connect
)

type Organization

type Organization struct {
	ID uint `json:"id" gorm:"primaryKey"`
	// Name is the globally unique handle (e.g. "default").
	Name string `json:"name" gorm:"uniqueIndex;not null"`
	// DisplayName is the free-text label shown in the UI.
	DisplayName string `json:"display_name"`
	// IsDefault marks the org new workspaces and providers attach to. Exactly one
	// row is the default.
	IsDefault bool `json:"is_default" gorm:"default:false;not null"`
	// EnforceSSO disables local password login for this org's users (Enterprise;
	// writing it is gated on the sso_saml entitlement). Off by default.
	EnforceSSO bool      `json:"enforce_sso" gorm:"default:false;not null"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

Organization is a realm owning identity configuration — SSO, SAML, enforced login, SCIM. Miabi seeds a single default organization spanning all workspaces. The table and nullable foreign keys exist from day one so multi-org needs no destructive migration.

type OwnerRef

type OwnerRef struct {
	Kind string `json:"kind"`           // one of OwnerKind*
	ID   uint   `json:"id,omitempty"`   // owning resource id (0 = none/not applicable)
	Name string `json:"name,omitempty"` // display name
}

OwnerRef is the parsed owner reference attached to a resource's metadata.

func Owner

func Owner(m Metadata) (OwnerRef, bool)

Owner parses the owner reference from m. ok is false when no owner kind is set.

type PasswordResetToken

type PasswordResetToken struct {
	ID        uint       `json:"id" gorm:"primaryKey"`
	UserID    uint       `json:"user_id" gorm:"index;not null"`
	TokenHash string     `json:"-" gorm:"uniqueIndex;not null"`
	ExpiresAt time.Time  `json:"expires_at" gorm:"not null"`
	UsedAt    *time.Time `json:"used_at"`
	CreatedAt time.Time  `json:"created_at"`
}

PasswordResetToken is a single-use, expiring password-reset credential.

type Permission

type Permission string

Permission is a fine-grained capability of the form "resource:action". Each built-in WorkspaceRole maps to a permission set reproducing rank-based RequireRole exactly (enforced by permission_test.go); custom roles are just alternative permission sets.

const (
	PermAppRead   Permission = "app:read"
	PermAppWrite  Permission = "app:write"  // create / update config / env / attach
	PermAppDeploy Permission = "app:deploy" // deploy / start / stop / restart / rollback / canary
	PermAppDelete Permission = "app:delete"
	PermAppAdmin  Permission = "app:admin" // reveal secrets, privileged host mounts

	PermDatabaseRead   Permission = "database:read"
	PermDatabaseWrite  Permission = "database:write"
	PermDatabaseDelete Permission = "database:delete"

	PermVolumeRead  Permission = "volume:read"
	PermVolumeWrite Permission = "volume:write"

	PermDomainRead  Permission = "domain:read"
	PermDomainWrite Permission = "domain:write"

	PermRouteRead  Permission = "route:read"
	PermRouteWrite Permission = "route:write"

	PermNetworkRead  Permission = "network:read"
	PermNetworkWrite Permission = "network:write"

	PermBackupRead    Permission = "backup:read"
	PermBackupRun     Permission = "backup:run"
	PermBackupRestore Permission = "backup:restore"

	PermSecretRead  Permission = "secret:read"
	PermSecretWrite Permission = "secret:write"

	PermConfigRead  Permission = "config:read"
	PermConfigWrite Permission = "config:write"

	PermMemberRead  Permission = "member:read"
	PermMemberWrite Permission = "member:write"

	PermWorkspaceWrite  Permission = "workspace:write"
	PermWorkspaceDelete Permission = "workspace:delete"
)

func AllPermissions

func AllPermissions() []Permission

AllPermissions returns the full catalog in a stable, grouped order (for the UI and the permission-picker in custom roles).

func (Permission) Action

func (p Permission) Action() string

Action returns the action segment ("deploy" for "app:deploy").

func (Permission) Resource

func (p Permission) Resource() string

Resource returns the resource segment of a permission ("app" for "app:deploy").

type PipelineCheckout added in v1.9.0

type PipelineCheckout string

PipelineCheckout names what a pipeline clones into the shared workspace before its steps run. Distinct from PipelineSource, which is about who owns the spec.

const (
	// CheckoutNone is a command-only pipeline: nothing is cloned, and steps run
	// against an empty workspace.
	CheckoutNone PipelineCheckout = "none"
	// CheckoutApplication clones the bound application's repository.
	CheckoutApplication PipelineCheckout = "application"
	// CheckoutRepository clones a registered Git repository directly.
	CheckoutRepository PipelineCheckout = "repository"
)

type PipelineDefinition

type PipelineDefinition struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_pipeline_ws_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace.
	Name string `json:"name" gorm:"index:idx_pipeline_ws_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	// ApplicationID optionally binds the pipeline to an application: the app
	// supplies the source to clone, the image repository to push to, and the
	// target a `uses: deploy` step deploys.
	ApplicationID   *uint `json:"application_id,omitempty" gorm:"index"`
	GitRepositoryID *uint `json:"git_repository_id,omitempty" gorm:"index"`
	// GitRepository is the bound repository's name, filled on read.
	GitRepository string `json:"git_repository,omitempty" gorm:"-"`
	Branch        string `json:"branch,omitempty"`
	// Spec is the raw kind: Pipeline YAML (on/steps). Parsed at run time.
	Spec          string `json:"spec" gorm:"type:text;not null"`
	Enabled       bool   `json:"enabled" gorm:"not null;default:true"`
	WebhookSecret string `json:"-" gorm:"not null;default:''"`

	// Source records who owns Spec. An empty value reads as manual, so pipelines
	// created before repository adoption existed keep behaving exactly as before.
	Source PipelineSource `json:"source,omitempty" gorm:"not null;default:manual"`
	// SourcePath is the repo-relative path Spec was read from (repo source only),
	// e.g. ".miabi/pipeline.yaml".
	SourcePath string `json:"source_path,omitempty"`
	// SourceRef is the branch or ref the spec is read from (repo source only).
	// It is the app's tracked ref at adoption time.
	SourceRef string `json:"source_ref,omitempty"`
	// SourceCommit is the commit Spec was last read at (repo source only) — what
	// the UI shows as "synced from <commit>".
	SourceCommit string `json:"source_commit,omitempty"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// LastRun is a non-persisted summary of the pipeline's most recent run,
	// populated by the list endpoint for an at-a-glance health signal. nil when
	// the pipeline has never run.
	LastRun *PipelineRunSummary `json:"last_run,omitempty" gorm:"-"`
}

PipelineDefinition is a versioned, pipeline-as-code definition (kind: Pipeline). The raw YAML spec is stored so the runner reads the same document the repo carries at .miabi/pipeline.yaml.

func (*PipelineDefinition) Checkout added in v1.9.0

func (p *PipelineDefinition) Checkout() PipelineCheckout

Checkout reports what this pipeline clones. The application binding wins when both are somehow set, though the service refuses to store that combination.

func (*PipelineDefinition) IsRepoOwned added in v1.6.8

func (p *PipelineDefinition) IsRepoOwned() bool

IsRepoOwned reports whether the repository owns this pipeline's spec, which makes it read-only in Miabi and re-read on every run.

type PipelineRun

type PipelineRun struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index;not null"`
	PipelineID  uint `json:"pipeline_id" gorm:"index;not null"`
	// Number is the per-pipeline monotonic run counter (#1, #2, …).
	Number int               `json:"number" gorm:"not null"`
	Status PipelineRunStatus `json:"status" gorm:"not null;default:pending"`
	// Trigger records how the run started: push | manual | schedule | upstream.
	Trigger string `json:"trigger"`
	// Branch is the ref the run built, surfaced to steps as $MIABI_BRANCH. Set
	// from the pushed ref, or from the app's tracked ref for a manual run.
	Branch        string `json:"branch,omitempty"`
	Commit        string `json:"commit,omitempty"`
	CommitMessage string `json:"commit_message,omitempty" gorm:"type:text"`
	// TriggeredByKeyID / TriggeredByUserID attribute the run (mirrors Deployment).
	TriggeredByKeyID  *uint `json:"triggered_by_key_id,omitempty"`
	TriggeredByUserID *uint `json:"triggered_by_user_id,omitempty"`
	// ImageID is the artifact the run produced (nil until the build step pushes).
	ImageID *uint `json:"image_id,omitempty"`
	// RunnerID records which runner executed this run (provenance / "built on
	// runner X"); nil when it ran on the internal runner.
	RunnerID *uint  `json:"runner_id,omitempty"`
	Error    string `json:"error,omitempty" gorm:"type:text"`
	// Env is the pipeline-level environment as written in the spec, applied to
	// every step. Stored unresolved, like the steps' own.
	Env map[string]string `json:"env,omitempty" gorm:"serializer:json"`
	// NoCache records that this run was asked to ignore the build cache, overriding whatever the spec's
	// `cache:` says. It is a per-run override, not a setting: the next run caches again unless it asks
	// too. Kept on the run because "why did this one take nine minutes?" is a question about the run.
	NoCache bool `json:"no_cache,omitempty" gorm:"not null;default:false"`

	StartedAt  *time.Time `json:"started_at,omitempty"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`

	Steps []PipelineStepRun `json:"steps,omitempty" gorm:"foreignKey:PipelineRunID"`
}

PipelineRun is one execution of a PipelineDefinition: build → test → … → deploy, turning a commit into an image and a Release.

func (PipelineRun) Summary

func (r PipelineRun) Summary() *PipelineRunSummary

Summary projects a run onto its list-view summary.

type PipelineRunStatus

type PipelineRunStatus string

PipelineRunStatus is the lifecycle state of a run or one of its steps.

const (
	PipelineRunPending   PipelineRunStatus = "pending"
	PipelineRunRunning   PipelineRunStatus = "running"
	PipelineRunSucceeded PipelineRunStatus = "succeeded"
	PipelineRunFailed    PipelineRunStatus = "failed"
	PipelineRunCanceled  PipelineRunStatus = "canceled"
)

func (PipelineRunStatus) IsTerminal

func (s PipelineRunStatus) IsTerminal() bool

IsTerminal reports whether the status is final.

type PipelineRunSummary

type PipelineRunSummary struct {
	ID         uint              `json:"id"`
	Number     int               `json:"number"`
	Status     PipelineRunStatus `json:"status"`
	Trigger    string            `json:"trigger,omitempty"`
	Commit     string            `json:"commit,omitempty"`
	StartedAt  *time.Time        `json:"started_at,omitempty"`
	FinishedAt *time.Time        `json:"finished_at,omitempty"`
	CreatedAt  time.Time         `json:"created_at"`
}

PipelineRunSummary is a lightweight view of a run for list contexts — enough to render a status badge and "ran 2h ago" without shipping steps or logs.

type PipelineSource added in v1.6.8

type PipelineSource string

PipelineSource records who owns a definition's spec.

const (
	// PipelineSourceManual is a spec authored in Miabi: the UI and API own it.
	PipelineSourceManual PipelineSource = "manual"
	// PipelineSourceRepo is a spec adopted from the repository's pipeline-as-code
	// file. The repo is the source of truth — the spec is re-read at each run's
	// commit, and Miabi refuses to edit it in place.
	PipelineSourceRepo PipelineSource = "repo"
)

type PipelineStepRun

type PipelineStepRun struct {
	ID            uint              `json:"id" gorm:"primaryKey"`
	PipelineRunID uint              `json:"pipeline_run_id" gorm:"index;not null"`
	Ordinal       int               `json:"ordinal" gorm:"not null"`
	Name          string            `json:"name" gorm:"not null"`
	Status        PipelineRunStatus `json:"status" gorm:"not null;default:pending"`
	Image         string            `json:"image,omitempty"`
	Uses          string            `json:"uses,omitempty"` // built-in step kind (e.g. "deploy")
	// Run is the shell command for a container (Image) step, executed in a non-login shell inside
	// the step image — like a GitHub Actions `run:` step — so pipes, && and env expansion work.
	// Empty for `uses:` built-in steps.
	Run string `json:"run,omitempty" gorm:"type:text"`
	// Dockerfile and BuildContext configure a `uses: build` step, relative to the checked-out
	// source root; empty means "Dockerfile" and the root. Recorded per RUN because a run is the
	// audit record of what was built, not of the definition as it reads today.
	Dockerfile   string `json:"dockerfile,omitempty"`
	BuildContext string `json:"build_context,omitempty"`
	// BuildArgs are the step's Dockerfile ARG values, recorded per run as part of what produced
	// the image. Not secrets — a build arg is readable from the image history — so they are
	// stored in the clear, unlike the run's credentials.
	BuildArgs map[string]string `json:"build_args,omitempty" gorm:"serializer:json"`
	// NoCache builds this step's image from scratch. It is the resolved answer for this run — the spec's
	// `cache: false` OR the run-level override — so the runner reads one field and the row records what
	// was actually asked of the builder.
	NoCache bool `json:"no_cache,omitempty" gorm:"not null;default:false"`
	// Env is the step's environment as written in the spec, references included:
	// the run records what was asked for, never a resolved secret value.
	Env map[string]string `json:"env,omitempty" gorm:"serializer:json"`
	// ContinueOnError lets the run keep going (and still succeed) when this step
	// fails; the step is still recorded failed.
	ContinueOnError bool   `json:"continue_on_error,omitempty"`
	ExitCode        int    `json:"exit_code"`
	Logs            string `json:"logs,omitempty" gorm:"type:text"`
	LogRef          string `json:"log_ref,omitempty"`
	LogBytes        int64  `json:"log_bytes,omitempty"`
	LogLines        int    `json:"log_lines,omitempty"`
	LogTruncated    bool   `json:"log_truncated,omitempty"`

	StartedAt  *time.Time `json:"started_at,omitempty"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`
}

PipelineStepRun is one step within a run, executed in an isolated container.

type Plan

type Plan struct {
	ID                        uint          `json:"id" gorm:"primaryKey"`
	Name                      string        `json:"name" gorm:"uniqueIndex;not null"`
	Description               string        `json:"description"`
	IsDefault                 bool          `json:"is_default" gorm:"not null;default:false"` // applied to workspaces with no plan
	IsActive                  bool          `json:"is_active" gorm:"not null;default:true"`
	System                    bool          `json:"system" gorm:"not null;default:false"`
	MaxApps                   int           `json:"max_apps" gorm:"not null;default:0"`
	MaxDatabaseInstances      int           `json:"max_database_instances" gorm:"not null;default:0"`
	MaxCronJobs               int           `json:"max_cron_jobs" gorm:"not null;default:0"`
	MaxVolumes                int           `json:"max_volumes" gorm:"not null;default:0"`
	MaxNetworks               int           `json:"max_networks" gorm:"not null;default:0"`
	MaxAPIKeys                int           `json:"max_api_keys" gorm:"not null;default:0"`
	MaxMembers                int           `json:"max_members" gorm:"not null;default:0"`
	MaxDatabasesPerInstance   int           `json:"max_databases_per_instance" gorm:"not null;default:0"`
	MaxCPUCores               int           `json:"max_cpu_cores" gorm:"not null;default:0"`
	MaxMemoryMB               int           `json:"max_memory_mb" gorm:"not null;default:0"`
	MaxDatabaseInstanceSizeMB int           `json:"max_database_instance_size_mb" gorm:"not null;default:0"`
	MaxStorageMB              int           `json:"max_storage_mb" gorm:"not null;default:0"`
	MaxRunners                int           `json:"max_runners" gorm:"not null;default:0"`
	MaxGPUs                   int           `json:"max_gpus" gorm:"not null;default:0"`
	MaxDatabaseCPUCores       int           `json:"max_database_cpu_cores" gorm:"not null;default:-1"` // database budget, apart from the apps'
	MaxDatabaseMemoryMB       int           `json:"max_database_memory_mb" gorm:"not null;default:-1"` // -1 by default: older plans stay unchanged
	AllowCustomTLS            bool          `json:"allow_custom_tls" gorm:"not null;default:false"`
	AllowPrivilegedHostMounts bool          `json:"allow_privileged_host_mounts" gorm:"not null;default:false"`
	AllowShellExec            bool          `json:"allow_shell_exec" gorm:"not null;default:false"`
	AllowSharedStorage        bool          `json:"allow_shared_storage" gorm:"not null;default:false"`
	AllowDNSProviders         bool          `json:"allow_dns_providers" gorm:"not null;default:false"`
	AllowCustomLabels         bool          `json:"allow_custom_labels" gorm:"not null;default:false"`
	AllowPlatformRunners      bool          `json:"allow_platform_runners" gorm:"not null;default:false"`
	AllowCustomBuilder        bool          `json:"allow_custom_builder" gorm:"not null;default:false"`
	SecurityProfile           string        `json:"security_profile" gorm:"not null;default:'default'"`
	AllowOfficialImageUser    bool          `json:"allow_official_image_user" gorm:"not null;default:false"`
	AllowGPU                  bool          `json:"allow_gpu" gorm:"not null;default:false"`
	Placement                 PlanPlacement `json:"placement" gorm:"type:text;serializer:json"`
	DatabaseSizes             []uint        `json:"database_sizes" gorm:"type:text;serializer:json"`
	StorageClasses            []string      `json:"storage_classes" gorm:"type:text;serializer:json"`
	DefaultStorageClass       string        `json:"default_storage_class"`
	CreatedAt                 time.Time     `json:"created_at"`
	UpdatedAt                 time.Time     `json:"updated_at"`
}

Plan is an admin-defined per-workspace quota + capability template. Numeric limits use -1 for unlimited and 0 for none; capability booleans gate features.

type PlanPlacement added in v1.10.0

type PlanPlacement struct {
	// Locations are the cluster ids the plan may use; the first is its default location.
	Locations []uint `json:"locations,omitempty"`
	Pool      string `json:"pool,omitempty"`
}

PlanPlacement binds a plan to locations and a node pool (Enterprise). No locations allows every location; no pool keeps the plan's workloads on nodes that are in no pool.

type PlatformBackup

type PlatformBackup struct {
	ID uint `json:"id" gorm:"primaryKey"`
	// SetID is the owning recovery point. A POINTER, not a plain uint: the association makes GORM
	// create a real foreign key, and an ad-hoc single-subject backup belongs to no set. Stored as
	// 0 it would reference a row that cannot exist, so NULL is what "no set" means.
	SetID      *uint                 `json:"set_id,omitempty" gorm:"index"`
	Subject    PlatformBackupSubject `json:"subject" gorm:"not null"`
	VolumeName string                `json:"volume_name,omitempty"` // target volume (volume subjects)

	// Tenant provenance, set on tenant-database and tenant-volume items. The slug
	// is stored alongside the id because a restore reads these from a recovery
	// point manifest, where a numeric id from a dead install means nothing.
	WorkspaceID   uint   `json:"workspace_id,omitempty" gorm:"index"`
	WorkspaceSlug string `json:"workspace_slug,omitempty"`
	DatabaseName  string `json:"database_name,omitempty"`
	Engine        string `json:"engine,omitempty"`

	Status      BackupStatus `json:"status" gorm:"not null;default:pending"`
	Trigger     string       `json:"trigger"`     // manual | scheduled
	Destination string       `json:"destination"` // local | s3
	// Encrypted records whether this artifact was actually written GPG-encrypted,
	// as opposed to what the settings say now — a run that predates the toggle
	// must still restore correctly.
	Encrypted bool `json:"encrypted"`

	S3Bucket  string `json:"s3_bucket,omitempty"`
	S3Path    string `json:"s3_path,omitempty"`  // remote folder prefix used
	Filename  string `json:"filename,omitempty"` // artifact object name
	SizeBytes int64  `json:"size_bytes"`

	Logs         string `json:"logs,omitempty" gorm:"type:text"`
	LogRef       string `json:"log_ref,omitempty"`
	LogBytes     int64  `json:"log_bytes,omitempty"`
	LogLines     int    `json:"log_lines,omitempty"`
	LogTruncated bool   `json:"log_truncated,omitempty"`
	Error        string `json:"error,omitempty" gorm:"type:text"`

	StartedAt  *time.Time `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at"`
	CreatedAt  time.Time  `json:"created_at"`
}

PlatformBackup is a single disaster-recovery run of the platform itself — the control-plane database or a platform volume. Distinct from the per-workspace Backup/VolumeBackup tables, and reuses BackupStatus and the one-shot/logging lifecycle.

type PlatformBackupSet added in v1.8.0

type PlatformBackupSet struct {
	ID uint `json:"id" gorm:"primaryKey"`

	// Ref is the stable, human-quotable name of this recovery point:
	// "mbdr_<install-id>_<UTC stamp>". It is what an operator passes to
	// `miabi restore --ref`, so it is unique and never reused.
	Ref     string       `json:"ref" gorm:"uniqueIndex;not null"`
	Trigger string       `json:"trigger"` // manual | scheduled
	Status  BackupStatus `json:"status" gorm:"not null;default:pending"`

	// Provenance — captured at set creation, checked by restore preflight.
	InstallID     string `json:"install_id"`
	MiabiVersion  string `json:"miabi_version"`
	SchemaVersion string `json:"schema_version"` // last applied upgrade step
	// KEKFingerprint proves two installs share a master encryption key without revealing it:
	// HMAC-SHA256(KEK, KEKFingerprintLabel) via crypto.DeriveToken. Restore recomputes it after
	// loading the identity envelope and refuses to continue on a mismatch.
	KEKFingerprint string `json:"kek_fingerprint"`
	Encrypted      bool   `json:"encrypted"`       // artifacts are GPG-encrypted
	IdentitySealed bool   `json:"identity_sealed"` // an identity envelope is present

	Destination string `json:"destination"` // local | s3
	S3Bucket    string `json:"s3_bucket,omitempty"`
	S3Path      string `json:"s3_path,omitempty"`
	SizeBytes   int64  `json:"size_bytes"`

	// Error carries why a set failed to complete (an item failing marks the set
	// failed: a partial recovery point is not a recovery point).
	Error string `json:"error,omitempty" gorm:"type:text"`

	StartedAt  *time.Time `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at"`
	CreatedAt  time.Time  `json:"created_at"`

	// Items are the artifacts of this recovery point. CASCADE because they have no
	// meaning without it: an artifact whose set is gone cannot be restored, and
	// leaving it behind would show a half a recovery point in the history.
	Items []PlatformBackup `json:"items,omitempty" gorm:"foreignKey:SetID;constraint:OnDelete:CASCADE"`
}

PlatformBackupSet groups one run's artifacts into a single recovery point: identity envelope, control-plane dump, and each volume archive. DR consumes a set, never a loose artifact. Provenance is read by the restore preflight before the target host is touched.

func (*PlatformBackupSet) Complete added in v1.8.0

func (s *PlatformBackupSet) Complete() bool

Complete reports whether the set is a usable recovery point: finished and carrying a control-plane dump. Volumes and the identity envelope are recorded separately — a set without an envelope can still be restored onto the original host.

func (*PlatformBackupSet) Item added in v1.8.0

Item returns the set's first item for a subject (and, for volumes, a name).

type PlatformBackupSettings

type PlatformBackupSettings struct {
	ID uint `json:"id" gorm:"primaryKey"`

	// Destination. S3/MinIO is the ONLY destination: a backup written to a volume on the host it
	// protects cannot be read once that host is gone, which is the one situation this exists for.
	// S3Enabled switches the feature off, it does not select an alternative.
	S3Enabled        bool   `json:"s3_enabled"`
	S3Endpoint       string `json:"s3_endpoint,omitempty"`
	S3Bucket         string `json:"s3_bucket,omitempty"`
	S3Region         string `json:"s3_region,omitempty"`
	S3AccessKey      string `json:"s3_access_key,omitempty"`
	S3SecretKeyEnc   string `json:"-" gorm:"column:s3_secret_key_enc"` // crypto.Encrypt (platform scope)
	S3UseSSL         bool   `json:"s3_use_ssl"`
	S3ForcePathStyle bool   `json:"s3_force_path_style"`

	// Path prefixes within the bucket. RootPath scopes the whole tree so one bucket can hold
	// several instances without colliding, and the recovery-point info file sits at its root.
	// Database and volume artifacts default to <root>/databases and <root>/volumes.
	RootPath           string `json:"root_path,omitempty"`
	DatabaseBackupPath string `json:"database_backup_path,omitempty"`
	VolumeBackupPath   string `json:"volume_backup_path,omitempty"`

	// Artifact encryption. EncryptBackups GPG-encrypts the dump and volume archives using
	// BackupPassphrase, which is NOT the master key (MIABI_ENCRYPTION_KEY) and must never be set
	// to it: a restore onto a fresh host cannot fetch a key that lived only on the dead one.
	EncryptBackups bool `json:"encrypt_backups"`
	// BackupPassphraseEnc is the passphrase at rest, encrypted under the master key — in the
	// database this feature backs up. Fine for taking backups and useless for restoring them, so
	// it is shown once on save and must be recorded out-of-band.
	BackupPassphraseEnc string `json:"-" gorm:"column:backup_passphrase_enc"`
	// IncludeIdentity seals the platform's identity (encryption key, JWT secret, install ID,
	// hostnames) into each recovery point so it can be restored onto a fresh host. Off only for
	// operators who custody /etc/miabi/miabi.yaml themselves.
	IncludeIdentity bool `json:"include_identity"`

	// IncludeTenantData adds every workspace's managed databases and volumes, so a restore brings
	// back tenant workloads and not just the control plane describing them. Off by default: it is
	// the difference between megabytes and the size of the install.
	IncludeTenantData bool `json:"include_tenant_data"`

	ScheduleEnabled bool     `json:"schedule_enabled"`
	ScheduleCron    string   `json:"schedule_cron,omitempty"`
	MaxBackups      int      `json:"max_backups"`
	RetentionDays   int      `json:"retention_days"`
	Volumes         []string `json:"volumes" gorm:"serializer:json"` // platform volumes to include

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// S3SecretSet reports whether a secret key is stored, without exposing it.
	// Not persisted; populated on read so the UI can render "••••• (set)".
	S3SecretSet bool `json:"s3_secret_set" gorm:"-"`
	// PassphraseSet likewise reports presence of the backup passphrase only.
	PassphraseSet bool `json:"passphrase_set" gorm:"-"`
	// EnvLocked names the fields supplied by environment variables on this
	// deployment. Those are read-only: the process configuration wins, and the UI
	// disables them rather than accepting an edit that would be silently ignored.
	EnvLocked []string `json:"env_locked,omitempty" gorm:"-"`
}

PlatformBackupSettings is the single-row platform backup target and policy: S3 destination, schedule, retention, and which platform volumes to include. The S3 secret is encrypted at rest with the platform-scoped crypto.Encrypt and never returned.

func (*PlatformBackupSettings) Normalize added in v1.8.0

func (s *PlatformBackupSettings) Normalize()

Normalize fills the derived defaults (database/volume prefixes, info-file format). Applied on both read and write, so a settings row saved before these fields existed behaves like a new one instead of scattering artifacts across the bucket root.

type PlatformBackupSubject

type PlatformBackupSubject string

PlatformBackupSubject identifies what a platform backup run captured: Miabi's own control-plane database, or one of the platform/system Docker volumes.

const (
	PlatformBackupDatabase PlatformBackupSubject = "database"
	PlatformBackupVolume   PlatformBackupSubject = "volume"
	// PlatformBackupIdentity is the sealed identity envelope: the platform's encryption key, JWT
	// secret and install identity, encrypted under the backup passphrase. It is what makes a dump
	// restorable onto a *different* host — see internal/dr.
	PlatformBackupIdentity PlatformBackupSubject = "identity"
	// PlatformBackupTenantDatabase and PlatformBackupTenantVolume are workload data: a
	// workspace's managed database or volume. They turn a recovery point from "the control plane
	// comes back" into "the platform comes back", and need IncludeTenantData.
	PlatformBackupTenantDatabase PlatformBackupSubject = "tenant-database"
	PlatformBackupTenantVolume   PlatformBackupSubject = "tenant-volume"
)

type PortBinding

type PortBinding struct {
	ID            uint              `json:"id" gorm:"primaryKey"`
	WorkspaceID   uint              `json:"workspace_id" gorm:"index;not null"`
	ApplicationID uint              `json:"application_id" gorm:"index;not null"`
	ContainerPort int               `json:"container_port" gorm:"not null"`
	Protocol      string            `json:"protocol" gorm:"not null;default:tcp"`
	HostPort      int               `json:"host_port" gorm:"not null"`
	Status        PortBindingStatus `json:"status" gorm:"not null;default:pending;index"`
	// ServerID is the node the host port is published on. Host ports are a
	// per-host resource, so conflict checks + allocation are scoped to it
	// (0 = the local/manager node). Backfilled from the owning app.
	ServerID    uint      `json:"server_id" gorm:"index;not null;default:0"`
	RequestedBy uint      `json:"requested_by"`
	ReviewedBy  *uint     `json:"reviewed_by,omitempty"`
	ReviewNote  string    `json:"review_note,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

PortBinding is a request to publish a container port on a host port. Because host ports are a node-wide shared resource, a binding is only published once a platform admin approves it.

type PortBindingStatus

type PortBindingStatus string

PortBindingStatus is the review state of a host port binding request.

const (
	PortBindingPending  PortBindingStatus = "pending"
	PortBindingApproved PortBindingStatus = "approved"
	PortBindingRejected PortBindingStatus = "rejected"
)

type ReclaimPolicy added in v1.10.2

type ReclaimPolicy string

ReclaimPolicy decides what happens to a class-backed volume's directory when the volume is deleted. A bind-backed Docker volume keeps its data after `docker volume rm`, so the platform has to say explicitly whether it removes it.

const (
	// ReclaimDelete removes the volume's directory under the class path.
	ReclaimDelete ReclaimPolicy = "delete"
	// ReclaimRetain keeps the directory; an admin reclaims it later.
	ReclaimRetain ReclaimPolicy = "retain"
)

type ReconcilePolicy added in v1.10.1

type ReconcilePolicy string

ReconcilePolicy is how much the control manager may do about this app, overriding the platform-wide mode. It exists because the first thing an operator wants, the first time a debugging session is undone by an automatic redeploy, is a way to exempt one app without switching the whole platform back to observing.

const (
	// ReconcileInherit follows the platform's control_manager_mode. The default.
	ReconcileInherit ReconcilePolicy = "inherit"
	// ReconcileOff leaves the app out of reconciliation entirely: not watched, not reported, not touched.
	ReconcileOff ReconcilePolicy = "off"
	// ReconcileObserve reports the app's drift but never acts on it, even while the platform enforces.
	ReconcileObserve ReconcilePolicy = "observe"
	// ReconcileEnforce lets the app be redeployed in place even while the platform only observes.
	ReconcileEnforce ReconcilePolicy = "enforce"
)

type Registry

type Registry struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_registry_workspace_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace.
	Name string `json:"name" gorm:"index:idx_registry_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	// Server is the registry host, e.g. "registry-1.docker.io", "ghcr.io",
	// "registry.gitlab.com". Empty defaults to Docker Hub.
	Server   string `json:"server"`
	Username string `json:"username"`
	// Secret holds the password or access token, encrypted at rest. Empty when the
	// credential points at the vault instead (see SecretRef).
	Secret string `json:"-" gorm:"not null"`
	// SecretRef names a workspace Secret holding the password instead of storing a copy here. The
	// value is read from the vault at every use, so rotating that secret rotates this credential.
	// Mutually exclusive with Secret; a name, so the API returns it.
	SecretRef string `json:"secret_ref,omitempty"`

	// Metadata holds free-form labels (provenance, grouping, GitOps). Keys under the reserved
	// "miabi.io/" prefix are platform-managed — the managed-by label is what keeps a GitOps prune
	// from deleting a credential created by hand.
	Metadata Metadata `json:"metadata,omitempty" gorm:"serializer:json"`
	// Annotations holds free-form, non-identifying descriptive metadata (the
	// manifest's metadata.annotations); no reserved keys. Persisted as JSON.
	Annotations Metadata `json:"annotations,omitempty" gorm:"serializer:json"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// HasSecret is a transient flag for responses (never persisted): true when the
	// credential can authenticate, whether from its own stored secret or a vault
	// reference.
	HasSecret bool `json:"has_secret" gorm:"-"`
}

Registry is a stored container-registry credential used to pull private images at deploy time. The Secret (password / access token) is encrypted at rest and never serialized.

type RegistrySettings

type RegistrySettings struct {
	ID uint `json:"id" gorm:"primaryKey"`

	// Enabled runs the registry container and seeds its gateway route/middleware.
	// Read-only: MIABI_REGISTRY_ENABLED. Default false → a no-op so single-node
	// installs are unchanged.
	Enabled bool `json:"enabled"`
	// Host is the public registry hostname (e.g. registry.<external-domain>),
	// the docker login target. Read-only: MIABI_REGISTRY_HOST, else derived from
	// the default cluster's external domain.
	Host string `json:"host,omitempty"`

	// StorageType is "filesystem" (a managed volume) or "s3" (S3/MinIO).
	// Read-only: MIABI_REGISTRY_STORAGE. The S3 driver additionally requires the
	// registry_s3 entitlement, enforced at container start.
	StorageType string `json:"storage_type" gorm:"not null;default:filesystem"`

	// Filesystem driver: the managed data volume. A fixed platform name.
	VolumeName string `json:"volume_name,omitempty"`

	// S3 / MinIO driver. Read-only: MIABI_REGISTRY_S3_*.
	S3Endpoint       string `json:"s3_endpoint,omitempty"`
	S3Bucket         string `json:"s3_bucket,omitempty"`
	S3Region         string `json:"s3_region,omitempty"`
	S3AccessKey      string `json:"s3_access_key,omitempty"`
	S3SecretKeyEnc   string `json:"-" gorm:"column:s3_secret_key_enc"` // crypto.Encrypt (platform scope)
	S3ForcePathStyle bool   `json:"s3_force_path_style"`

	// DeleteEnabled turns on the registry's delete API (a prerequisite for GC).
	DeleteEnabled bool `json:"delete_enabled"`
	// PerWorkspaceQuotaMB caps a workspace namespace's total blob size (0 = none).
	PerWorkspaceQuotaMB int `json:"per_workspace_quota_mb"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// S3SecretSet reports whether a secret key is stored, without exposing it.
	// Not persisted; populated on read so the UI can render "••••• (set)".
	S3SecretSet bool `json:"s3_secret_set" gorm:"-"`
}

RegistrySettings is the single-row, platform-scoped config for the built-in Docker registry (one per platform, mirroring PlatformBackupSettings). The S3 secret is encrypted at rest. Only DeleteEnabled and PerWorkspaceQuotaMB are writable; the rest is environment-derived.

func (*RegistrySettings) UsesS3

func (r *RegistrySettings) UsesS3() bool

UsesS3 reports whether the registry is configured for the S3 storage driver.

type Release

type Release struct {
	ID            uint   `json:"id" gorm:"primaryKey"`
	ApplicationID uint   `json:"application_id" gorm:"index:idx_release_app_version,unique;index;not null"`
	DeploymentID  uint   `json:"deployment_id" gorm:"not null"`
	Version       int    `json:"version" gorm:"index:idx_release_app_version,unique;not null"`
	Image         string `json:"image" gorm:"not null"`
	ContainerID   string `json:"container_id"`
	Active        bool   `json:"active" gorm:"not null;default:false"`
	Adopted       bool   `json:"adopted" gorm:"not null;default:false"`
	Pinned        bool   `json:"pinned" gorm:"not null;default:false"`
	Digest        string `json:"digest,omitempty"`                       // sha256:… the release ran
	Commit        string `json:"commit,omitempty"`                       // source commit, when known
	PipelineRunID *uint  `json:"pipeline_run_id,omitempty" gorm:"index"` // producing run
	ImageID       *uint  `json:"image_id,omitempty" gorm:"index"`        // catalog artifact
	EnvironmentID *uint  `json:"environment_id,omitempty" gorm:"index"`  // promotion stage

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

Release is a successfully deployed, rollback-able version of an application.

type ReleaseApproval

type ReleaseApproval struct {
	ID            uint      `json:"id" gorm:"primaryKey"`
	WorkspaceID   uint      `json:"workspace_id" gorm:"index;not null"`
	ReleaseID     uint      `json:"release_id" gorm:"index;not null"`
	EnvironmentID *uint     `json:"environment_id,omitempty" gorm:"index"`
	ApproverID    uint      `json:"approver_id" gorm:"not null"`
	Approved      bool      `json:"approved" gorm:"not null;default:true"`
	Comment       string    `json:"comment,omitempty"`
	CreatedAt     time.Time `json:"created_at"`
}

ReleaseApproval records one approver's decision on promoting a release into an environment. A promotion needs Environment.RequiredApprovals approvals.

type ResourcePolicy

type ResourcePolicy struct {
	ID           uint      `json:"id" gorm:"primaryKey"`
	WorkspaceID  uint      `json:"workspace_id" gorm:"index:idx_resource_policy;not null"`
	UserID       uint      `json:"user_id" gorm:"index:idx_resource_policy;not null"`
	ResourceType string    `json:"resource_type" gorm:"index:idx_resource_policy;not null"`
	ResourceID   uint      `json:"resource_id" gorm:"index:idx_resource_policy;not null"`
	Permissions  []string  `json:"permissions" gorm:"serializer:json"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`

	User User `json:"user,omitempty" gorm:"foreignKey:UserID"`
}

ResourcePolicy grants a user permissions on a single resource (Enterprise, gated on resource_policies for writes). It augments the workspace role: a member may be a viewer everywhere yet hold app:deploy on one specific app. The table is empty in Community.

func (*ResourcePolicy) Grants

func (p *ResourcePolicy) Grants(perm Permission) bool

Grants reports whether the policy includes a permission.

type RestartPolicy

type RestartPolicy string

RestartPolicy is the Docker restart policy applied to an app's container. It mirrors the engine's policies; the platform default is "unless-stopped".

const (
	RestartNo            RestartPolicy = "no"
	RestartAlways        RestartPolicy = "always"
	RestartUnlessStopped RestartPolicy = "unless-stopped" // restart unless explicitly stopped (default)
	RestartOnFailure     RestartPolicy = "on-failure"     // restart only on non-zero exit
)

type Route

type Route struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_route_workspace_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace (Goma route name).
	Name string `json:"name" gorm:"index:idx_route_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName   string       `json:"display_name"`
	ApplicationID uint         `json:"application_id" gorm:"index;not null"`
	Path          string       `json:"path" gorm:"not null;default:/"`
	Hosts         []string     `json:"hosts,omitempty" gorm:"serializer:json"`
	Methods       []string     `json:"methods,omitempty" gorm:"serializer:json"`
	Middlewares   []string     `json:"middlewares,omitempty" gorm:"serializer:json"` // middleware names
	Rewrite       string       `json:"rewrite,omitempty"`                            // path rewrite (Goma route rewrite)
	TargetPort    int          `json:"target_port"`                                  // 0 = use the app's port
	TLSMode       RouteTLSMode `json:"tls_mode" gorm:"not null;default:acme"`
	// TLSProvider names the Goma certManager provider that issues/serves this
	// route's cert (the multi-provider certManager). Empty = the gateway default.
	TLSProvider string `json:"tls_provider,omitempty"`
	// Generated marks a platform-generated external-access route (managed from the
	// app's External access card, shown read-only in the Routes UI).
	Generated bool `json:"generated" gorm:"not null;default:false"`
	// AdvancedConfig is a raw Goma route YAML the admin authors directly; when
	// set, it supersedes the structured fields at render time (Miabi still
	// injects name + backends + tls so the route can't misroute). Empty = simple.
	AdvancedConfig string `json:"advanced_config,omitempty" gorm:"type:text"`
	// CertificateID references a stored Certificate when TLSMode=custom.
	CertificateID *uint `json:"certificate_id,omitempty" gorm:"index"`
	// Certificate declares the FK so deleting the referenced certificate nulls
	// this pointer (ON DELETE SET NULL) instead of leaving it dangling. The route
	// falls back to its default TLS mode. Association is not serialized.
	Certificate       *Certificate     `json:"-" gorm:"foreignKey:CertificateID;constraint:OnDelete:SET NULL"`
	Enabled           bool             `json:"enabled" gorm:"not null;default:true"`
	ExploitProtection bool             `json:"exploit_protection" gorm:"not null;default:false"`
	Maintenance       RouteMaintenance `json:"maintenance" gorm:"serializer:json"`
	// Status is the route's config-sync status, set whenever the workspace proxy
	// config is reconciled.
	Status RouteStatus `json:"status" gorm:"not null;default:pending"`
	// StatusReason explains a non-live status (e.g. "domain not verified",
	// "disabled", or the gateway write error). Empty when live.
	StatusReason string `json:"status_reason,omitempty"`
	// SyncedAt is when the route was last reconciled into the gateway config.
	SyncedAt *time.Time `json:"synced_at,omitempty"`
	// Metadata holds free-form labels; "miabi.io/" keys are platform-managed.
	Metadata  Metadata  `json:"metadata,omitempty" gorm:"serializer:json"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// HasCustomCert is a transient flag for responses (never persisted).
	HasCustomCert bool `json:"has_custom_cert" gorm:"-"`

	// DNSTarget / DNSHostname are the public address an A/AAAA (or CNAME) record
	// for this route's hosts should point to — the gateway that terminates the
	// route. Transient, populated on read.
	DNSTarget   string `json:"dns_target,omitempty" gorm:"-"`
	DNSHostname string `json:"dns_hostname,omitempty" gorm:"-"`

	// Backends are the actual upstream endpoints (DNS aliases) the gateway uses for this route.
	// Transient, populated on read so the UI shows the real backend.
	Backends []string `json:"backends,omitempty" gorm:"-"`
}

Route is a Goma Gateway route owned by a workspace and bound to an application. The container backend is injected by the platform at render time (the app's network alias), so users never set it.

type RouteMaintenance added in v1.8.3

type RouteMaintenance struct {
	Enabled    bool   `json:"enabled"`
	StatusCode int    `json:"status_code,omitempty"`
	Message    string `json:"message,omitempty"`
}

type RouteStatus

type RouteStatus string

RouteStatus is a route's config-sync status with the gateway — whether Goma is actually serving the route's config. It is NOT upstream health: RouteLive means "Goma is configured to serve this route", not "the backend answers 200".

const (
	// RouteStatusPending is the initial state before the route has been synced.
	RouteStatusPending RouteStatus = "pending"
	// RouteStatusLive means the route was synced and Goma is serving it (enabled,
	// and every host falls under a verified domain).
	RouteStatusLive RouteStatus = "live"
	// RouteStatusOffline means the route is synced but not served — it is disabled,
	// or one of its hosts is not under a verified domain (rendered enabled:false).
	RouteStatusOffline RouteStatus = "offline"
	// RouteStatusError means the last attempt to push the route's config to the
	// gateway failed; StatusReason carries the detail.
	RouteStatusError RouteStatus = "error"
)

type RouteTLSMode

type RouteTLSMode string

RouteTLSMode selects how TLS is served for a route's hosts.

const (
	RouteTLSNone   RouteTLSMode = "none"
	RouteTLSACME   RouteTLSMode = "acme"   // Goma's global ACME issuer
	RouteTLSCustom RouteTLSMode = "custom" // user-supplied certificate
)

type Runner

type Runner struct {
	UIDModel
	ID uint `json:"id" gorm:"primaryKey"`
	// Name is a URL-safe slug handle, unique within its owner (per workspace for
	// owned runners; among shared runners for platform ones).
	Name string `json:"name" gorm:"index:idx_runner_ws_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI (defaults to Name).
	DisplayName string `json:"display_name"`
	// WorkspaceID is nil for platform-shared runners, set for workspace-owned
	// ones. Part of the (workspace_id, name) uniqueness index.
	WorkspaceID *uint       `json:"workspace_id,omitempty" gorm:"index:idx_runner_ws_name,unique"`
	Scope       RunnerScope `json:"scope" gorm:"not null;default:workspace"`
	// Labels route jobs to eligible runners (e.g. "arch=amd64", "buildkit",
	// "gpu"). A job runs only where its required labels are a subset of these.
	Labels []string `json:"labels,omitempty" gorm:"serializer:json"`
	// Concurrency is how many jobs the runner may lease at once (declared by the
	// operator; the scheduler tracks live leases against it).
	Concurrency int `json:"concurrency" gorm:"not null;default:1"`

	// Self-reported platform facts (filled on connect).
	OS      string `json:"os,omitempty"`
	Arch    string `json:"arch,omitempty"`
	Version string `json:"version,omitempty"`
	// RemoteIP is the source address of the runner's most recent tunnel
	// connection (last known; persists across disconnects for the detail view).
	RemoteIP string `json:"remote_ip,omitempty"`

	Status RunnerStatus `json:"status" gorm:"not null;default:offline"`
	// Cordoned holds the runner out of scheduling without disconnecting it
	// (operator pause), mirroring Server.Cordoned.
	Cordoned bool `json:"cordoned" gorm:"not null;default:false"`
	// Enabled is the admin/owner on-off switch; a disabled runner never receives
	// jobs even if connected. Defaults true.
	Enabled bool `json:"enabled" gorm:"not null;default:true"`
	// TokenHash is the SHA-256 of the one-time registration token; the plaintext
	// is shown once at creation and never stored (mirrors Server.TokenHash).
	TokenHash string `json:"-" gorm:"index"`
	// Ephemeral marks a per-job, autoscaled runner (spun up for one job and torn
	// down after). Standing runners are non-ephemeral. Reserved for the later
	// autoscaling phase; excluded from the owned-runner quota when set.
	Ephemeral bool `json:"ephemeral" gorm:"not null;default:false"`
	// Connected reflects a live tunnel (transient; set by the connection manager).
	Connected bool `json:"connected" gorm:"-"`

	LastSeenAt *time.Time `json:"last_seen_at,omitempty"`
	// ConnectedSince is when the current unbroken connection began — reset on reconnect, cleared
	// on disconnect. LastSeenAt cannot answer "how long has this runner been up?" because the
	// heartbeat refreshes it every 30s, which the offline alert needs to survive flapping.
	ConnectedSince *time.Time `json:"connected_since,omitempty"`
	CreatedByID    *uint      `json:"created_by_id,omitempty"`

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

Runner is a machine dedicated to build and pipeline execution: it leases jobs, runs each step in an isolated container, pushes the image, and reports status — app nodes only pull the digest. Either workspace-owned (Scope=workspace) or platform-shared (Scope=shared).

type RunnerLease

type RunnerLease struct {
	ID       uint `json:"id" gorm:"primaryKey"`
	RunnerID uint `json:"runner_id" gorm:"index;not null"`
	// Kind namespaces RunID (pipeline run vs deploy build); see LeaseKind.
	Kind LeaseKind `json:"kind" gorm:"not null;default:pipeline"`
	// RunID is the job this lease claims (a PipelineRun or a Deployment, per Kind).
	// A partial unique index on (kind, run_id) for active rows enforces the
	// at-most-one active claim per job at the DB level.
	RunID  uint  `json:"run_id" gorm:"index;not null"`
	StepID *uint `json:"step_id,omitempty"`

	Status   RunnerLeaseStatus `json:"status" gorm:"not null;default:active;index"`
	LeasedAt time.Time         `json:"leased_at"`
	// ExpiresAt is the lease deadline; a live runner renews it, a dead one lets it
	// lapse (→ requeue). Mirrors the job deadline.
	ExpiresAt time.Time `json:"expires_at" gorm:"index"`

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

RunnerLease is a runner's at-most-once claim on a job (per Kind) and optionally a step, created on lease and released when the job goes terminal. An active lease past ExpiresAt is a dead runner: the sweeper expires it and the job requeues.

type RunnerLeaseStatus

type RunnerLeaseStatus string

RunnerLeaseStatus is the state of a runner's claim on a pipeline run.

const (
	// LeaseActive: the runner holds the job and is executing it. Exactly one
	// active lease may exist per run (the at-most-once claim).
	LeaseActive RunnerLeaseStatus = "active"
	// LeaseDone: the run reached a terminal state and the lease was released.
	LeaseDone RunnerLeaseStatus = "done"
	// LeaseExpired: the lease passed its deadline without completing (a dead
	// runner); the sweeper requeues the run onto another runner.
	LeaseExpired RunnerLeaseStatus = "expired"
)

type RunnerScope

type RunnerScope string

RunnerScope is who may schedule jobs onto a runner.

const (
	// ScopeWorkspace: a runner registered and owned by a single workspace; only
	// that workspace's jobs run on it (WorkspaceID is set).
	ScopeWorkspace RunnerScope = "workspace"
	// ScopeShared: a platform-shared runner (WorkspaceID is nil) usable by any
	// workspace whose plan grants the platform-runners capability. Managed by
	// admins, mirroring a global TemplateSource/OAuthProvider.
	ScopeShared RunnerScope = "shared"
)

type RunnerStatus

type RunnerStatus string

RunnerStatus is the reachability state of a runner, mirroring ServerStatus.

const (
	// RunnerStatusOnline: the runner has a live tunnel and is leasing jobs.
	RunnerStatusOnline RunnerStatus = "online"
	// RunnerStatusOffline: no live tunnel (never connected, or heartbeat lapsed).
	RunnerStatusOffline RunnerStatus = "offline"
	// RunnerStatusDraining: connected but finishing its in-flight jobs before it
	// disconnects (no new leases). Distinct from Cordoned, which is an operator
	// hold applied while the runner may still be online.
	RunnerStatusDraining RunnerStatus = "draining"
)

type RuntimeKind

type RuntimeKind string

RuntimeKind is how an app runs: a single Docker container (default) or a replicated Swarm service. Auto-gated on the manager being a swarm manager — a "service" app only deploys when cluster mode is enabled.

const (
	// RuntimeContainer runs the app as one plain Docker container on its node.
	RuntimeContainer RuntimeKind = "container"
	// RuntimeService runs the app as a replicated Swarm service on the workspace
	// overlay network.
	RuntimeService RuntimeKind = "service"
)

type SAMLConfig

type SAMLConfig struct {
	ID             uint  `json:"id" gorm:"primaryKey"`
	OrganizationID *uint `json:"organization_id" gorm:"index"`
	// Name is the globally unique handle.
	Name string `json:"name" gorm:"uniqueIndex;not null"`
	// DisplayName is the free-text label shown in the UI.
	DisplayName string `json:"display_name"`

	// IdP metadata: a URL to fetch, or inline XML. One of the two is required.
	IDPMetadataURL string `json:"idp_metadata_url"`
	IDPMetadataXML string `json:"idp_metadata_xml" gorm:"type:text"`

	// SPEntityID overrides the service-provider entity ID (defaults to the SP
	// metadata URL when blank).
	SPEntityID string `json:"sp_entity_id"`

	// Attribute names mapping the assertion onto the user. Blank falls back to
	// the standard "email" / "displayName" (and the NameID for email).
	AttrEmail string `json:"attr_email"`
	AttrName  string `json:"attr_name"`

	Enabled   bool      `json:"enabled" gorm:"default:true;not null"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

SAMLConfig is a SAML 2.0 identity-provider connection for an organization. The table is migrated in every build but is only read/written by the enterprise SAML handler (gated on the sso_saml entitlement); it stays empty in Community.

type SCIMToken

type SCIMToken struct {
	ID             uint       `json:"id" gorm:"primaryKey"`
	OrganizationID *uint      `json:"organization_id" gorm:"index"`
	Name           string     `json:"name" gorm:"not null"`
	TokenHash      string     `json:"-" gorm:"uniqueIndex;not null"`
	LastUsedAt     *time.Time `json:"last_used_at"`
	CreatedAt      time.Time  `json:"created_at"`
}

SCIMToken is a bearer credential an identity provider uses to call the SCIM 2.0 endpoint. Only the SHA-256 hash is stored; the plaintext is shown once at creation. Migrated in every build but only used by the enterprise SCIM handler (gated on the scim entitlement).

type SIEMConfig

type SIEMConfig struct {
	ID       uint   `json:"id" gorm:"primaryKey"`
	Name     string `json:"name" gorm:"not null"`
	Sink     string `json:"sink" gorm:"not null"`         // syslog | webhook | s3
	Endpoint string `json:"endpoint"`                     // syslog addr / webhook URL / s3 bucket+prefix
	Format   string `json:"format" gorm:"default:'json'"` // json | cef
	// AuthHeaderEnc is a webhook Authorization value, encrypted at rest. Never
	// serialized.
	AuthHeaderEnc string `json:"-" gorm:"column:auth_header"`
	Enabled       bool   `json:"enabled" gorm:"default:true;not null"`

	// LastShippedID is the durable cursor: the highest audit-log id confirmed
	// shipped to this sink. The streamer only advances it after a successful ship.
	LastShippedID uint       `json:"last_shipped_id"`
	LastError     string     `json:"last_error"`
	LastShippedAt *time.Time `json:"last_shipped_at"`

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

SIEMConfig is one external audit-streaming target (Enterprise, gated on siem_stream). The streamer ships audit events at-least-once and records progress in LastShippedID, a durable cursor surviving restarts and sink outages. The table is empty in Community.

type Secret

type Secret struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_secret_workspace_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace; env refs use it.
	Name string `json:"name" gorm:"index:idx_secret_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	ValueEnc    string `json:"-" gorm:"column:value_enc;type:text"` // encrypted
	Description string `json:"description"`
	// Version bumps on each value change (rotation), for display/rollback.
	Version     int   `json:"version" gorm:"not null;default:1"`
	UpdatedByID *uint `json:"updated_by_id,omitempty"`

	// Managed marks a secret auto-created and owned by a platform resource (e.g.
	// a managed database). Its value is derived (rotate via the owner, not by
	// hand) and its lifecycle follows the owner. OwnerKind/OwnerID identify it.
	Managed   bool   `json:"managed" gorm:"not null;default:false"`
	OwnerKind string `json:"owner_kind,omitempty" gorm:"index:idx_secret_owner"`
	OwnerID   uint   `json:"owner_id,omitempty" gorm:"index:idx_secret_owner"`

	// Metadata holds free-form labels; "miabi.io/" keys are platform-managed.
	Metadata  Metadata  `json:"metadata,omitempty" gorm:"serializer:json"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Secret is a workspace-scoped named secret (the Vault). Env values reference it by name (`${{ secrets.NAME }}`); the reference is resolved into a container's environment at deploy/job time and never returned by the API. The value is encrypted at rest.

type Server

type Server struct {
	UIDModel
	ID           uint               `json:"id" gorm:"primaryKey"`
	Name         string             `json:"name" gorm:"uniqueIndex;not null"`
	DisplayName  string             `json:"display_name"`
	ClusterID    uint               `json:"cluster_id" gorm:"index;not null;default:0"`
	Connectivity ServerConnectivity `json:"connectivity" gorm:"not null;default:cluster"`
	// AccessMode is how the control plane reaches this node's Docker engine.
	// Existing rows backfill to "agent" (column default); the local node is set
	// to "socket" at bootstrap.
	AccessMode ServerAccessMode `json:"access_mode" gorm:"not null;default:agent"`
	// DockerEndpoint is the Docker host for non-agent modes: unix://… (socket) or
	// tcp://host:2376 (api). Unused for agent.
	DockerEndpoint string `json:"docker_endpoint"`
	IsLocal        bool   `json:"is_local" gorm:"not null;default:false"`
	// Role is the node's cluster role: "manager" for the control-plane node,
	// "node" for workers.
	Role       ServerRole   `json:"role" gorm:"not null;default:node"`
	Status     ServerStatus `json:"status" gorm:"not null;default:unknown"`
	LastSeenAt *time.Time   `json:"last_seen_at"`

	// api (TCP) TLS material — optional (plaintext when empty). PEM-encoded; the
	// private key is encrypted at rest and never serialized.
	TLSCACert string `json:"-" gorm:"type:text"`
	TLSCert   string `json:"-" gorm:"type:text"`
	TLSKeyEnc string `json:"-" gorm:"column:tls_key_enc;type:text"`
	// TLSEnabled is a transient flag for responses (whether TLS material is set).
	TLSEnabled bool `json:"tls_enabled" gorm:"-"`

	// Remote-node fields.
	// Address is the host/IP the reverse proxy uses to reach this node's
	// published app ports (e.g. "10.0.0.7").
	Address string `json:"address,omitempty"`

	// TokenHash is the SHA-256 of the agent join token; the plaintext is shown
	// once at creation and never stored.
	TokenHash       string `json:"-" gorm:"index"`
	GatewayTokenEnc string `json:"-"`
	// GatewayDeployedAt is when the node's gateway was last deployed (display).
	GatewayDeployedAt *time.Time `json:"gateway_deployed_at,omitempty"`
	GatewayConfigYAML string     `json:"-" gorm:"type:text"`
	// GatewayImage overrides the edge-gateway image/tag for this node; empty =
	// the resolved catalog/default image.
	GatewayImage     string `json:"gateway_image,omitempty"`
	GatewayContainer string `json:"gateway_container,omitempty"`
	// GatewayImported marks that the node's gateway was adopted from a pre-existing
	// container rather than deployed by Miabi.
	GatewayImported         bool                   `json:"gateway_imported" gorm:"not null;default:false"`
	GatewayRedisPasswordEnc string                 `json:"-"`
	GatewayUpdate           *GatewayUpdateProgress `json:"gateway_update,omitempty" gorm:"serializer:json"`
	// AgentConnected reflects a live agent tunnel (transient; set by the
	// connection manager).
	AgentConnected bool              `json:"agent_connected" gorm:"-"`
	AgentVersion   string            `json:"agent_version,omitempty"`
	EngineVersion  string            `json:"engine_version,omitempty"`
	Cordoned       bool              `json:"cordoned" gorm:"not null;default:false"`
	Labels         map[string]string `json:"labels,omitempty" gorm:"serializer:json"`
	SwarmNodeID    string            `json:"swarm_node_id,omitempty" gorm:"index"`
	AutoJoined     bool              `json:"auto_joined" gorm:"not null;default:false"`
	SwarmRole      string            `json:"swarm_role,omitempty" gorm:"-"`
	// SwarmAvailability is the scheduling availability: active | pause | drain.
	SwarmAvailability string `json:"swarm_availability,omitempty" gorm:"-"`
	// SwarmState is the swarm-reported reachability: ready | down | unknown |
	// disconnected.
	SwarmState string `json:"swarm_state,omitempty" gorm:"-"`
	// InSwarm reports whether this node is currently a member of the swarm.
	InSwarm bool `json:"in_swarm" gorm:"-"`

	// Capacity as DOCKER reports it, refreshed by the node capacity sweep. Docker's figures are
	// cgroup-aware, so they describe the node even when it is itself a container or a limited VM —
	// unlike /proc, which describes the machine underneath.
	CPUCores    int   `json:"cpu_cores" gorm:"not null;default:0"`
	MemoryBytes int64 `json:"memory_bytes" gorm:"not null;default:0"`
	// StorageBytes and StorageFreeBytes size the filesystem holding Docker's data root — the disk
	// images, containers and unclassed volumes actually consume.
	StorageBytes     int64 `json:"storage_bytes" gorm:"not null;default:0"`
	StorageFreeBytes int64 `json:"storage_free_bytes" gorm:"not null;default:0"`
	// CapacityMeasuredAt is nil on a node never measured, which is not the same as a node with no
	// capacity: totals skip it rather than adding zero.
	CapacityMeasuredAt *time.Time `json:"capacity_measured_at,omitempty"`

	// Last measured usage. Recorded only when the sample describes THIS node; a node whose /proc
	// reports its physical host is left unmeasured rather than contributing another machine's load.
	CPUPercent      float64    `json:"cpu_percent" gorm:"not null;default:0"`
	MemUsedBytes    int64      `json:"mem_used_bytes" gorm:"not null;default:0"`
	UsageMeasuredAt *time.Time `json:"usage_measured_at,omitempty"`

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

Server is a Docker host (node). The local node runs alongside the control plane; remote nodes run a `miabi agent` that dials in and exposes their Docker engine over a tunnel.

func (*Server) Label added in v1.7.2

func (s *Server) Label() string

type ServerAccessMode

type ServerAccessMode string

ServerAccessMode is how the control plane reaches a node's Docker engine. Distinct from ServerConnectivity (how the proxy reaches apps).

const (
	// AccessSocket: a local/Unix (or custom) Docker host where the control plane
	// runs (DockerEndpoint, e.g. unix:///var/run/docker.sock). The control-plane
	// node uses this.
	AccessSocket ServerAccessMode = "socket"
	// AccessAgent: the node's agent dials in over a tunnel (NAT-friendly, no
	// inbound ports on the node). DockerEndpoint is unused.
	AccessAgent ServerAccessMode = "agent"
	// AccessAPI: the control plane dials the node's Docker API over TCP
	// (DockerEndpoint = tcp://host:2376), optionally with TLS/mTLS.
	AccessAPI ServerAccessMode = "api"
)

type ServerConnectivity

type ServerConnectivity string

ServerConnectivity is how the platform reaches apps running on a node.

const (
	// ConnectivityEdgeGateway: the node runs its own gateway (public ingress, its
	// own TLS) that pulls its routes from the control plane's HTTP provider.
	ConnectivityEdgeGateway ServerConnectivity = "edge-gateway"
	// ConnectivityCluster: the node has no gateway of its own; its cluster's gateway serves its apps, over
	// the overlay for a swarm member. The control-plane node is one too.
	ConnectivityCluster ServerConnectivity = "cluster"
)

type ServerRole

type ServerRole string

ServerRole is a node's role in the cluster.

const (
	// RoleManager is the control-plane node that runs Miabi itself (the
	// platform manager). There is exactly one, and it reaches Docker via its local
	// socket.
	RoleManager ServerRole = "manager"
	// RoleNode is a worker node that only runs workloads.
	RoleNode ServerRole = "node"
)

type ServerStatus

type ServerStatus string

ServerStatus is the reachability state of a node.

const (
	ServerStatusOnline  ServerStatus = "online"
	ServerStatusOffline ServerStatus = "offline"
	ServerStatusUnknown ServerStatus = "unknown"
)

type ServiceEndpointMode added in v1.10.0

type ServiceEndpointMode string

ServiceEndpointMode is how a cluster's swarm services are reached by name.

const (
	// ServiceEndpointVIP gives each service one virtual IP that Docker balances across its tasks with IPVS.
	ServiceEndpointVIP ServiceEndpointMode = "vip"
	// ServiceEndpointDNSRR resolves a service's name to its tasks' own addresses, for hosts where Docker cannot
	// program IPVS, such as LXC containers.
	ServiceEndpointDNSRR ServiceEndpointMode = "dnsrr"
)

type ServiceUpdateConfig

type ServiceUpdateConfig struct {
	Parallelism  int `json:"parallelism,omitempty"`
	DelaySeconds int `json:"delay_seconds,omitempty"`
}

ServiceUpdateConfig tunes how Swarm rolls out a service update for cluster apps (parallelism = tasks updated at once; delay = pause between batches).

type Session

type Session struct {
	ID        uint      `json:"id" gorm:"primaryKey"`
	UserID    uint      `json:"user_id" gorm:"index;not null"`
	JTI       string    `json:"jti" gorm:"uniqueIndex;not null;size:36"`
	IPAddress string    `json:"ip_address"`
	UserAgent string    `json:"user_agent" gorm:"size:512"`
	Revoked   bool      `json:"revoked" gorm:"default:false;not null"`
	CreatedAt time.Time `json:"created_at"`
	ExpiresAt time.Time `json:"expires_at"`
}

Session tracks an active JWT session for a user (revocable via its JTI).

func (*Session) IsActive

func (s *Session) IsActive() bool

IsActive reports whether the session is neither revoked nor expired.

type Setting

type Setting struct {
	ID        uint        `json:"id" gorm:"primaryKey"`
	Key       string      `json:"key" gorm:"uniqueIndex;not null"`
	Value     string      `json:"value" gorm:"type:text"`
	Type      SettingType `json:"type" gorm:"default:string;not null"`
	CreatedAt time.Time   `json:"created_at"`
	UpdatedAt time.Time   `json:"updated_at"`

	// Pinned reports that an environment variable supplies this value. Not
	// persisted: populated on read so the console can show the field as
	// operator-managed instead of offering an edit that reverts on restart.
	Pinned bool `json:"pinned" gorm:"-"`
}

Setting is a single global, platform-wide key/value configuration entry. The value is always stored as a string; Type records how to parse it.

type SettingType

type SettingType string

SettingType describes how a setting's string value should be interpreted.

const (
	SettingTypeString SettingType = "string"
	SettingTypeInt    SettingType = "int"
	SettingTypeBool   SettingType = "bool"
	SettingTypeJSON   SettingType = "json"
)

type Stack

type Stack struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_stack_workspace_name,unique;not null"`
	// Name is the unique slug handle scoped to the workspace.
	Name string `json:"name" gorm:"index:idx_stack_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	DockerName  string `json:"docker_name" gorm:"uniqueIndex;not null"`
	ClusterID   uint   `json:"cluster_id" gorm:"index;not null;default:0"`
	// DockerNetwork is the platform-managed Docker network shared by the stack's
	// apps, giving them service-name DNS discovery isolated from other stacks.
	DockerNetwork string `json:"docker_network,omitempty"`
	Description   string `json:"description,omitempty"`
	// Metadata holds free-form labels; "miabi.io/" keys are platform-managed.
	Metadata Metadata `json:"metadata,omitempty" gorm:"serializer:json"`
	// Annotations holds free-form, non-identifying descriptive metadata (the
	// manifest's metadata.annotations); no reserved keys. Persisted as JSON.
	Annotations Metadata  `json:"annotations,omitempty" gorm:"serializer:json"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`

	// Apps are the applications assigned to this stack. Populated on the stack
	// detail view; an application belongs to at most one stack.
	Apps []Application `json:"apps,omitempty" gorm:"foreignKey:StackID"`
}

Stack groups related applications in a workspace so they can be managed together. Name is unique per workspace; DockerName is the platform-managed Compose project name applied as the com.docker.compose.project label, so Docker tooling groups them too.

func (*Stack) BeforeCreate added in v1.10.0

func (s *Stack) BeforeCreate(tx *gorm.DB) error

type StackEnvVar

type StackEnvVar struct {
	ID        uint      `json:"id" gorm:"primaryKey"`
	StackID   uint      `json:"stack_id" gorm:"index:idx_stack_env_key,unique;not null"`
	Key       string    `json:"key" gorm:"index:idx_stack_env_key,unique;not null"`
	Value     string    `json:"value"` // plaintext for non-secret; ciphertext when IsSecret
	IsSecret  bool      `json:"is_secret" gorm:"not null;default:false"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// OverriddenBy names the member applications that define the same key. An
	// app-level variable wins, so a shared value can be inert for some members;
	// derived on read rather than stored.
	OverriddenBy []string `json:"overridden_by,omitempty" gorm:"-"`
}

StackEnvVar is a shared environment variable injected into every member application's containers at deploy time. App-level vars with the same key take precedence. Secret values are encrypted at rest.

type StorageClass added in v1.10.2

type StorageClass struct {
	UIDModel
	ID uint `json:"id" gorm:"primaryKey"`
	// Name is the handle the API, the CLI and manifests use. IMMUTABLE: volumes and GitOps
	// manifests reference a class by name, and manifests live in repositories Miabi cannot
	// rewrite, so a rename would orphan or silently redirect them.
	Name        string `json:"name" gorm:"uniqueIndex;not null"`
	DisplayName string `json:"display_name"`
	Description string `json:"description,omitempty"`
	// ServerID is the node the path exists on (0 = the local control-plane node).
	ServerID uint `json:"server_id" gorm:"index;not null;default:0"`
	// ServerName is the node's display name (transient; populated on read).
	ServerName string `json:"server_name,omitempty" gorm:"-"`
	ClusterID  uint   `json:"cluster_id" gorm:"index;not null;default:0"`
	// Path is the Miabi-owned directory volumes are created under, as <Path>/<DockerName>. Empty
	// means Docker's own data root (the built-in class). IMMUTABLE: volumes already exist under it,
	// so re-pointing it would not move data — it would point live volumes at the wrong directory.
	Path string `json:"path"`
	// Shared records the operator's assertion that this path is the same filesystem on every node
	// of the cluster, which is what allows a replicated service to rely on it.
	Shared bool `json:"shared" gorm:"not null;default:false"`
	// IsDefault marks the class used when a create names none. At most one per node.
	IsDefault bool `json:"is_default" gorm:"not null;default:false"`
	// Enabled off blocks new volumes; existing ones keep working.
	Enabled       bool          `json:"enabled" gorm:"not null;default:true"`
	ReclaimPolicy ReclaimPolicy `json:"reclaim_policy" gorm:"not null;default:delete"`
	// Builtin marks the seeded "default" class: it cannot be deleted, and its key and path are
	// fixed even by the rules that already make those immutable.
	Builtin bool `json:"builtin" gorm:"not null;default:false"`
	// CapacityBytes and AvailableBytes are the filesystem's measured size, refreshed by the storage
	// sweep. 0 with a nil MeasuredAt means never measured.
	CapacityBytes  int64      `json:"capacity_bytes" gorm:"not null;default:0"`
	AvailableBytes int64      `json:"available_bytes" gorm:"not null;default:0"`
	MeasuredAt     *time.Time `json:"measured_at,omitempty"`
	CreatedAt      time.Time  `json:"created_at"`
	UpdatedAt      time.Time  `json:"updated_at"`
}

StorageClass is an admin-approved directory on a node where Miabi creates volumes. The tenant names a class; the platform derives the path — so an unprivileged workspace can use operator storage without ever supplying a host path (unlike VolumeDriverHost).

func (*StorageClass) Managed added in v1.10.2

func (c *StorageClass) Managed() bool

Managed reports whether the class puts volumes on an operator-chosen path rather than leaving them to Docker's data root.

func (*StorageClass) VolumePath added in v1.10.2

func (c *StorageClass) VolumePath(dockerName string) string

VolumePath is the directory a volume with the given Docker name occupies under this class. Empty for the built-in class, which has no path of its own.

type SystemRole

type SystemRole string
const (
	SystemRoleAdmin SystemRole = "admin" // platform super-admin
	SystemRoleUser  SystemRole = "user"
)

type Template

type Template struct {
	ID       uint `json:"id" gorm:"primaryKey"`
	SourceID uint `json:"source_id" gorm:"index:idx_template_src_name_ver,unique;not null"`
	// Name is the stable template handle (e.g. "ghost").
	Name string `json:"name" gorm:"index:idx_template_src_name_ver,unique;not null"`
	// Version is the manifest semver; unique per (source, name).
	Version string `json:"version" gorm:"index:idx_template_src_name_ver,unique;not null"`
	// DisplayName is the free-text catalog label (e.g. "Ghost").
	DisplayName string         `json:"display_name"`
	Category    string         `json:"category,omitempty"`
	Icon        string         `json:"icon,omitempty"`
	Digest      string         `json:"digest,omitempty"`
	RawYAML     string         `json:"-" gorm:"type:text"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`
}

Template is one version of a catalog entry, synced from a source. RawYAML is the manifest as authored; the parsed form is re-derived on demand.

type TemplateInstall

type TemplateInstall struct {
	ID          uint   `json:"id" gorm:"primaryKey"`
	WorkspaceID uint   `json:"workspace_id" gorm:"index;not null"`
	Source      string `json:"source"` // official | community | custom
	// TemplateName is the template handle installed from (references Template.Name).
	TemplateName string `json:"template_name" gorm:"index;not null"`
	// TemplateDisplayName is the catalog label snapshot at install time.
	TemplateDisplayName string `json:"template_display_name"`
	// DisplayName is the label the user gave *this install*, which every resource
	// it creates is named after. Recorded so an upgrade can name a resource the
	// new version adds the same way the install named the rest.
	DisplayName string `json:"display_name,omitempty"`
	Version     string `json:"version"`
	StackID     *uint  `json:"stack_id,omitempty" gorm:"index"`
	AppIDs      []uint `json:"app_ids,omitempty" gorm:"serializer:json"`
	DatabaseIDs []uint `json:"database_ids,omitempty" gorm:"serializer:json"`
	VolumeIDs   []uint `json:"volume_ids,omitempty" gorm:"serializer:json"`
	// ConfigIDs maps a template-local config name to the workspace config created
	// for it. A map rather than a list of ids because an upgrade has to resolve
	// "the config this version calls X" — and the workspace name it was given may
	// carry a uniqueness suffix that cannot be recomputed.
	ConfigIDs map[string]uint `json:"config_ids,omitempty" gorm:"serializer:json"`
	// Inputs holds the non-secret install answers, for re-install/upgrade prompts.
	Inputs    map[string]string `json:"inputs,omitempty" gorm:"serializer:json"`
	CreatedAt time.Time         `json:"created_at"`
}

TemplateInstall records that a stack/app(s) were installed from a template, so the UI can show provenance ("installed from Ghost 1.2.0") and later offer upgrade/uninstall.

type TemplateSource

type TemplateSource struct {
	ID          uint               `json:"id" gorm:"primaryKey"`
	WorkspaceID *uint              `json:"workspace_id,omitempty" gorm:"index"`
	Name        string             `json:"name" gorm:"not null"`
	Type        TemplateSourceType `json:"type" gorm:"not null"`
	URL         string             `json:"url,omitempty"`
	Ref         string             `json:"ref,omitempty"`         // git branch/tag
	GitRepoID   *uint              `json:"git_repo_id,omitempty"` // optional stored credential
	Official    bool               `json:"official" gorm:"not null;default:false"`
	Verified    bool               `json:"verified" gorm:"not null;default:false"`
	SyncStatus  string             `json:"sync_status,omitempty"` // idle | syncing | error
	LastSynced  *time.Time         `json:"last_synced,omitempty"`
	LastError   string             `json:"last_error,omitempty"`
	CreatedAt   time.Time          `json:"created_at"`
	UpdatedAt   time.Time          `json:"updated_at"`
	DeletedAt   gorm.DeletedAt     `json:"-" gorm:"index"`
}

TemplateSource is where templates come from. Global sources (WorkspaceID nil) are admin-managed; a custom source is per-workspace.

type TemplateSourceType

type TemplateSourceType string

TemplateSourceType is where a set of templates comes from.

const (
	TemplateSourceBuiltin TemplateSourceType = "builtin" // embedded official catalog
	TemplateSourceGit     TemplateSourceType = "git"     // a Git repo with an index.yaml
	TemplateSourceHTTP    TemplateSourceType = "http"    // a remote index.yaml
	TemplateSourceCustom  TemplateSourceType = "custom"  // per-workspace user imports
)

type Theme added in v1.9.4

type Theme string
const (
	ThemeSystem Theme = "system"
	ThemeLight  Theme = "light"
	ThemeDark   Theme = "dark"
)

type TwoFactorRecoveryCode

type TwoFactorRecoveryCode struct {
	ID        uint       `json:"id" gorm:"primaryKey"`
	UserID    uint       `json:"user_id" gorm:"index;not null"`
	CodeHash  string     `json:"-" gorm:"uniqueIndex;not null"`
	UsedAt    *time.Time `json:"used_at"`
	CreatedAt time.Time  `json:"created_at"`
}

TwoFactorRecoveryCode is a single-use backup code for two-factor authentication. Only the sha256 hash of the code is stored; the plaintext is shown to the user once at generation time.

type UIDModel

type UIDModel struct {
	UID string `json:"uid" gorm:"type:uuid;uniqueIndex;not null;default:gen_random_uuid()"`
}

UIDModel is an embeddable mixin giving a resource a stable UUIDv7 alongside its uint primary key: the PK stays the internal handle, the uid is the portable external one (Terraform id, GitOps/backup reference, non-enumerable public handle). Embed it anonymously.

func (*UIDModel) BeforeCreate

func (m *UIDModel) BeforeCreate(*gorm.DB) error

BeforeCreate assigns a UUIDv7 when one was not supplied. A caller may preset UID (e.g. import/restore keeping an incoming identity); only an empty value is generated.

type UpdateStatus

type UpdateStatus struct {
	ID uint `json:"-" gorm:"primaryKey"`
	// LatestVersion is the newest release for the running build's channel, as a
	// semver tag with the leading "v" (e.g. "v1.0.0-beta.5"). Empty until the
	// first successful check.
	LatestVersion string     `json:"latest_version"`
	ReleaseURL    string     `json:"release_url"`
	PublishedAt   *time.Time `json:"published_at"`
	// ETag from the last successful GitHub response. Replayed as If-None-Match so
	// an unchanged release list answers 304, which costs no API quota.
	ETag string `json:"-"`
	// CheckedVersion is the running build that produced LatestVersion. The ETag fingerprints only
	// the release list, so after an upgrade GitHub answers 304 and a verdict computed for the OLD
	// build would stick. Storing it lets Check notice the build moved and redo the comparison.
	CheckedVersion string `json:"-"`
	// CheckedAt is the last *attempt*; LastError explains a failing one. Both are
	// admin-visible so a silently broken checker cannot masquerade as "up to date".
	CheckedAt *time.Time `json:"checked_at"`
	LastError string     `json:"last_error,omitempty"`
	// DismissedVersion is the version an admin chose to stop being notified about.
	// Platform-wide: only platform admins ever see the notice.
	DismissedVersion string    `json:"dismissed_version,omitempty"`
	UpdatedAt        time.Time `json:"-"`
}

UpdateStatus caches the result of the daily release check. Exactly one row (ID 1) ever exists: it is platform state, not a user-editable setting, so it deliberately lives outside the `settings` table, whose every row is listed and editable on the admin page.

type UpgradeProgress

type UpgradeProgress struct {
	FromVersion string `json:"from_version"`
	ToVersion   string `json:"to_version"`
	Path        string `json:"path"`  // "in-place" | "dump-restore"
	Phase       string `json:"phase"` // backing-up | stopping-apps | swapping | dumping | restoring | cutover | verifying | starting-apps | done | failed
	Error       string `json:"error,omitempty"`
}

UpgradeProgress is the live state of an in-flight version upgrade, surfaced on the instance while Status is "upgrading" (and briefly after, on failure).

type UpgradeStep

type UpgradeStep struct {
	ID        uint      `json:"id" gorm:"primaryKey"`
	Version   string    `json:"version" gorm:"index;not null"`
	Name      string    `json:"name" gorm:"uniqueIndex;not null"`
	AppliedAt time.Time `json:"applied_at"`
}

UpgradeStep records an applied, versioned data-upgrade step so it runs at most once. Schema changes use GORM AutoMigrate; data backfills use steps.

type User

type User struct {
	ID                       uint       `json:"id" gorm:"primaryKey"`
	Name                     string     `json:"name" gorm:"not null;default:''"`
	Username                 string     `json:"username" gorm:"uniqueIndex;not null"`
	Email                    string     `json:"email" gorm:"uniqueIndex;not null"`
	PasswordHash             string     `json:"-" gorm:"not null"`
	Role                     SystemRole `json:"role" gorm:"default:user;not null"`
	TwoFactorSecret          string     `json:"-" gorm:"type:text"`
	TwoFactorEnabled         bool       `json:"two_factor_enabled" gorm:"default:false;not null"`
	Active                   bool       `json:"active" gorm:"default:true;not null"`
	MustChangePassword       bool       `json:"must_change_password" gorm:"not null;default:false"`
	AuthSource               string     `json:"auth_source" gorm:"not null;default:'local'"`
	WorkspaceLimit           *int       `json:"workspace_limit,omitempty"`
	WorkspaceMembershipLimit *int       `json:"workspace_membership_limit,omitempty"`
	ScheduledDeletionAt      *time.Time `json:"scheduled_deletion_at" gorm:"index"`
	EmailVerifiedAt          *time.Time `json:"email_verified_at"`
	LastLoginAt              *time.Time `json:"last_login_at"`
	OnboardingDismissedAt    *time.Time `json:"onboarding_dismissed_at"`
	DefaultWorkspaceID       *uint      `json:"default_workspace_id" gorm:"index"`
	CreatedAt                time.Time  `json:"created_at"`
	UpdatedAt                time.Time  `json:"updated_at"`
}

User is a global identity.

func (*User) BeforeCreate

func (u *User) BeforeCreate(tx *gorm.DB) error

func (*User) IsAdmin

func (u *User) IsAdmin() bool

type UserSetting added in v1.9.4

type UserSetting struct {
	ID     uint `json:"-" gorm:"primaryKey"`
	UserID uint `json:"-" gorm:"uniqueIndex;not null"`

	Theme Theme `json:"theme" gorm:"size:10;not null;default:system"`
	// Accent is EMPTY until the user picks one, which is not the same as picking
	// the default: an unset accent inherits the operator's brand accent, and a
	// chosen one does not. Resolved on read; see usersettings.
	Accent      Accent `json:"accent" gorm:"size:16;not null;default:''"`
	Timezone    string `json:"timezone" gorm:"size:64;not null;default:UTC"`
	Locale      string `json:"locale" gorm:"size:10;not null;default:en"`
	LandingView string `json:"landing_view" gorm:"size:32;not null;default:dashboard"`
	// AccentLocked means the operator enforces the brand accent, so Accent is theirs
	// and the console offers no choice. Resolved on read, never stored.
	AccentLocked bool `json:"accent_locked" gorm:"-"`

	CreatedAt time.Time `json:"-"`
	UpdatedAt time.Time `json:"-"`
}

func DefaultUserSetting added in v1.9.4

func DefaultUserSetting() UserSetting

type VerifiedVia added in v1.9.4

type VerifiedVia string

VerifiedVia records how a domain's ownership was established. It is the difference between a proof and a waiver: only a DNS proof can go stale, so only a DNS proof may be revoked by the drift cron.

const (
	// VerifiedViaDNS is ownership proven by the challenge TXT record.
	VerifiedViaDNS VerifiedVia = "dns"
	// VerifiedViaDNSProvider is the same proof, on a domain whose records Miabi
	// manages through a connected DNS provider.
	VerifiedViaDNSProvider VerifiedVia = "dns_provider"
	// VerifiedViaAdmin is a platform-admin override (ForceVerify) — a waiver granted
	// for private or otherwise unreachable DNS, not a proof of ownership.
	VerifiedViaAdmin VerifiedVia = "admin"
)

func (VerifiedVia) IsWaiver added in v1.9.4

func (v VerifiedVia) IsWaiver() bool

IsWaiver reports whether ownership was granted rather than proven. A waiver is never revoked by the drift cron: there is no record for it to lose.

type Volume

type Volume struct {
	UIDModel
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_vol_workspace_name,unique;not null"`
	// Name is the unique, URL/CLI/docker handle (lowercase [a-z0-9-]) scoped to the
	// workspace.
	Name string `json:"name" gorm:"index:idx_vol_workspace_name,unique;not null"`
	// DisplayName is the free-text label shown in the UI.
	DisplayName string `json:"display_name"`
	DockerName  string `json:"docker_name" gorm:"uniqueIndex;not null"`
	// ServerID is the node this volume lives on (0 = local control-plane node).
	ServerID  uint `json:"server_id" gorm:"index;not null;default:0"`
	ClusterID uint `json:"cluster_id" gorm:"index;not null;default:0"`
	// ServerName is the display name of the node (transient; populated on read).
	ServerName      string     `json:"server_name,omitempty" gorm:"-"`
	Mountpoint      string     `json:"-"`
	EngineCreatedAt string     `json:"engine_created_at,omitempty"`
	SizeBytes       int64      `json:"size_bytes" gorm:"not null;default:0"`
	UsedBytes       int64      `json:"used_bytes" gorm:"not null;default:0"`
	UsedMeasuredAt  *time.Time `json:"used_measured_at,omitempty"`
	Imported        bool       `json:"imported" gorm:"not null;default:false"`
	// Shared storage (cluster mode). Driver is the Docker volume driver: "local"
	// (default, node-local) or "nfs"/"cifs" (a backend a replicated service can
	// share across nodes). AccessMode follows from it: local => rwo, shared => rwx.
	Driver string `json:"driver" gorm:"not null;default:local"`
	// AccessMode is rwo (node-local, single node) or rwx (shared, multi-node). The
	// guardrails use it to refuse replicating an app backed by an rwo volume.
	AccessMode VolumeAccessMode `json:"access_mode" gorm:"not null;default:rwo"`
	// DriverOptsEnc is the encrypted JSON of the driver's mount options (which may
	// include a CIFS password). Set at create time, never returned. The volume is
	// immutable, so options can't be edited after creation.
	DriverOptsEnc    string `json:"-" gorm:"type:text"`
	StorageClassName string `json:"storage_class" gorm:"not null;default:default"`
	// HostPath is the operator-managed host directory a "host" driver volume binds
	// (under /mnt/*). Empty for every other driver. Not a secret — it is the bind
	// source, mounted directly into the app's containers on each node.
	HostPath string `json:"host_path,omitempty"`
	// Metadata holds free-form labels; "miabi.io/" keys are platform-managed.
	Metadata Metadata `json:"metadata,omitempty" gorm:"serializer:json"`
	// Annotations holds free-form, non-identifying descriptive metadata (the
	// manifest's metadata.annotations); no reserved keys. Persisted as JSON.
	Annotations Metadata  `json:"annotations,omitempty" gorm:"serializer:json"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

Volume is a workspace-owned, managed Docker volume for persistent data.

func (*Volume) BeforeCreate added in v1.10.0

func (v *Volume) BeforeCreate(tx *gorm.DB) error

type VolumeAccessMode

type VolumeAccessMode string

VolumeAccessMode is how many nodes can mount a volume read-write at once.

const (
	// AccessRWO (ReadWriteOnce): a node-local volume usable by one node at a time
	// (the default "local" driver). A replicated service must NOT mount one, or
	// each node would silently get its own empty copy.
	AccessRWO VolumeAccessMode = "rwo"
	// AccessRWX (ReadWriteMany): a shared volume (NFS/CIFS/Ceph) every replica can
	// mount at once, so a stateful service can run with replicas > 1.
	AccessRWX VolumeAccessMode = "rwx"
)

type VolumeBackup

type VolumeBackup struct {
	ID          uint         `json:"id" gorm:"primaryKey"`
	WorkspaceID uint         `json:"workspace_id" gorm:"index;not null"`
	VolumeID    uint         `json:"volume_id" gorm:"index;not null"`
	ServerID    uint         `json:"server_id" gorm:"index;not null;default:0"` // node the volume lives on
	VolumeName  string       `json:"volume_name"`                               // docker volume name
	Status      BackupStatus `json:"status" gorm:"not null;default:pending"`
	Trigger     string       `json:"trigger"` // manual | scheduled

	S3Bucket  string `json:"s3_bucket,omitempty"`
	S3Path    string `json:"s3_path,omitempty"`  // remote folder prefix used
	Filename  string `json:"filename,omitempty"` // archive object name
	SizeBytes int64  `json:"size_bytes"`

	Logs         string `json:"logs,omitempty" gorm:"type:text"`
	LogRef       string `json:"log_ref,omitempty"`
	LogBytes     int64  `json:"log_bytes,omitempty"`
	LogLines     int    `json:"log_lines,omitempty"`
	LogTruncated bool   `json:"log_truncated,omitempty"`
	Error        string `json:"error,omitempty" gorm:"type:text"`

	StartedAt  *time.Time `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at"`
	CreatedAt  time.Time  `json:"created_at"`
}

VolumeBackup is a single backup run of a managed volume's contents, archived (compressed) to the workspace's S3 target. Reuses BackupStatus.

type Webhook

type Webhook struct {
	ID          uint     `json:"id" gorm:"primaryKey"`
	WorkspaceID uint     `json:"workspace_id" gorm:"index;not null"`
	Name        string   `json:"name"`
	URL         string   `json:"url" gorm:"not null"`
	Secret      string   `json:"-" gorm:"not null"`
	Events      []string `json:"events" gorm:"serializer:json"`
	// Headers are extra HTTP headers sent with each delivery (e.g. an
	// Authorization header for the receiving service).
	Headers map[string]string `json:"headers,omitempty" gorm:"serializer:json"`
	Enabled bool              `json:"enabled" gorm:"not null;default:true"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// HasSecret is a transient flag for responses (never persisted).
	HasSecret bool `json:"has_secret" gorm:"-"`
	// PlainSecret carries the generated secret in the create response only.
	PlainSecret string `json:"secret,omitempty" gorm:"-"`
}

Webhook is a workspace-registered HTTP endpoint receiving a signed JSON payload when a subscribed application event fires. The signing Secret is encrypted at rest and never serialized (a transient HasSecret flag instead); it is returned in cleartext once.

type WebhookDelivery

type WebhookDelivery struct {
	ID          uint   `json:"id" gorm:"primaryKey"`
	WebhookID   uint   `json:"webhook_id" gorm:"index;not null"`
	WorkspaceID uint   `json:"workspace_id" gorm:"index;not null"`
	Event       string `json:"event" gorm:"not null"`
	// EventID is the source AppEvent, enabling exact redelivery. 0 for tests.
	EventID        uint                  `json:"event_id,omitempty"`
	Status         WebhookDeliveryStatus `json:"status" gorm:"type:varchar(16);not null;index"`
	HTTPStatusCode int                   `json:"http_status_code"`
	ErrorMessage   string                `json:"error_message,omitempty"`
	Attempt        int                   `json:"attempt" gorm:"not null;default:1"`
	CreatedAt      time.Time             `json:"created_at"`
}

WebhookDelivery records the outcome of delivering one event to one webhook. One row is written per attempt; Attempt is the 1-based attempt number.

type WebhookDeliveryStatus

type WebhookDeliveryStatus string

WebhookDeliveryStatus is the terminal outcome of a delivery attempt chain.

const (
	WebhookDeliverySuccess WebhookDeliveryStatus = "success"
	WebhookDeliveryFailed  WebhookDeliveryStatus = "failed"
)

type Workspace

type Workspace struct {
	UIDModel
	ID uint `json:"id" gorm:"primaryKey"`
	// Name is the unique, URL/CLI/docker handle (lowercase [a-z0-9-]). It is the
	// human key for scoped routes and the registry namespace; the numeric ID/UID
	// remain the stable internal references.
	Name string `json:"name" gorm:"uniqueIndex;not null"`
	// DisplayName is the free-text label shown in the UI; not unique.
	DisplayName string `json:"display_name"`
	Description string `json:"description"`
	OwnerID     uint   `json:"owner_id" gorm:"index;not null"`
	// OrganizationID is the realm this workspace belongs to (nullable → the
	// default org). Lets SSO/enforced-login/SCIM scope to an org without a
	// destructive migration when multi-org lands.
	OrganizationID *uint `json:"organization_id" gorm:"index"`
	Privileged     bool  `json:"privileged" gorm:"not null;default:false"`
	// System marks the built-in platform workspace ("Miabi System"). It holds platform-managed
	// apps such as the per-node Goma gateways, is created on first boot, is always privileged,
	// and cannot be deleted. Only platform admins manage it.
	System bool `json:"system" gorm:"not null;default:false"`
	// PlanID is the assigned plan (nil → the default plan → unlimited). Drives
	// per-workspace resource quotas when plan enforcement is enabled.
	PlanID *uint `json:"plan_id,omitempty" gorm:"index"`
	// DefaultClusterID is the location a create lands in when it names none; nil means the default cluster.
	DefaultClusterID *uint     `json:"default_cluster_id,omitempty" gorm:"index"`
	CreatedAt        time.Time `json:"created_at"`
	UpdatedAt        time.Time `json:"updated_at"`

	Members []WorkspaceMember `json:"-" gorm:"foreignKey:WorkspaceID"`
}

Workspace is the multi-tenant root that owns all resources.

type WorkspaceBackupSettings

type WorkspaceBackupSettings struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"uniqueIndex;not null"`

	S3Enabled        bool   `json:"s3_enabled"`
	S3Endpoint       string `json:"s3_endpoint,omitempty"`
	S3Bucket         string `json:"s3_bucket,omitempty"`
	S3Region         string `json:"s3_region,omitempty"`
	S3AccessKey      string `json:"s3_access_key,omitempty"`
	S3SecretKeyEnc   string `json:"-" gorm:"column:s3_secret_key_enc"` // encrypted at rest
	S3UseSSL         bool   `json:"s3_use_ssl"`
	S3ForcePathStyle bool   `json:"s3_force_path_style"`

	// Path prefixes within the bucket (one shared bucket, three prefixes).
	DatabaseBackupPath string `json:"database_backup_path,omitempty"`
	VolumeBackupPath   string `json:"volume_backup_path,omitempty"`
	BundlePath         string `json:"bundle_path,omitempty"`

	// BundlePassphraseEnc is the bundle passphrase at rest, encrypted with the
	// workspace's data-encryption key.
	BundlePassphraseEnc string `json:"-" gorm:"column:bundle_passphrase_enc"`

	// BackupPassphraseEnc encrypts database backup artifacts, at rest itself under the
	// workspace's data-encryption key. Set means every new database backup leaves the
	// platform as GPG ciphertext; unset preserves the previous cleartext behaviour.
	BackupPassphraseEnc string `json:"-" gorm:"column:backup_passphrase_enc"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// S3SecretSet reports whether a secret key is stored, without exposing it.
	// Not persisted; populated on read so the UI can render "••••• (set)".
	S3SecretSet         bool `json:"s3_secret_set" gorm:"-"`
	BundlePassphraseSet bool `json:"bundle_passphrase_set" gorm:"-"`
	BackupPassphraseSet bool `json:"backup_passphrase_set" gorm:"-"`
}

func (*WorkspaceBackupSettings) BundlePrefix added in v1.7.0

func (s *WorkspaceBackupSettings) BundlePrefix() string

BundlePrefix is the effective bundle prefix for the workspace.

type WorkspaceBundle added in v1.7.0

type WorkspaceBundle struct {
	ID          uint                `json:"id" gorm:"primaryKey"`
	WorkspaceID uint                `json:"workspace_id" gorm:"index;not null"`
	Kind        WorkspaceBundleKind `json:"kind" gorm:"not null;default:export"`
	// Ref is the bundle's name in the bucket ("mbwb_<workspace>_<timestamp>"). On
	// a restore it is the bundle that was read.
	Ref    string       `json:"ref" gorm:"index"`
	Status BackupStatus `json:"status" gorm:"not null;default:pending"`
	Phase  string       `json:"phase,omitempty"`
	// Trigger is manual for now; scheduled bundles reuse the same row.
	Trigger string `json:"trigger,omitempty"`

	// TargetWorkspaceID is where a restore puts what it reads — usually the run's own workspace,
	// differing when a bundle lands in a fresh one (a clone or migration). Zero on an export. The
	// run stays owned by the workspace whose bucket it read.
	TargetWorkspaceID uint `json:"target_workspace_id,omitempty" gorm:"index"`
	// RestoreData pulls the dumps and archives as well as the configuration. Off
	// restores the shape of a workspace without its contents — useful to stage a
	// clone before committing to moving gigabytes.
	RestoreData bool `json:"restore_data"`
	// DeployApps rolls out the restored applications at the end of a restore.
	DeployApps bool `json:"deploy_apps"`

	S3Bucket string `json:"s3_bucket,omitempty"`
	S3Prefix string `json:"s3_prefix,omitempty"`
	// SourceWorkspace is the workspace the bundle was taken from, by name. On a
	// restore into a differently-named workspace it is the only record of where
	// the data came from.
	SourceWorkspace string `json:"source_workspace,omitempty"`

	// Artifacts / SizeBytes summarize what the run moved.
	Artifacts int   `json:"artifacts"`
	SizeBytes int64 `json:"size_bytes"`

	// Report is the human-readable outcome: what was created, skipped or could not be carried. A
	// restore's report is the deliverable — it names the manual follow-ups (DNS, certificates,
	// unverified domains) — so it is persisted rather than logged and lost.
	Report BundleReport `json:"report,omitempty" gorm:"serializer:json"`

	Logs       string     `json:"logs,omitempty" gorm:"type:text"`
	Error      string     `json:"error,omitempty" gorm:"type:text"`
	CreatedBy  *uint      `json:"created_by,omitempty"`
	StartedAt  *time.Time `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at"`
	CreatedAt  time.Time  `json:"created_at"`
}

WorkspaceBundle is one export or restore run of a portable workspace bundle. Separate from Backup/VolumeBackup, which record one artifact each against a live resource: a bundle run records a whole workspace crossing a boundary, listed in its own info file in the bucket.

type WorkspaceBundleKind added in v1.7.0

type WorkspaceBundleKind string

WorkspaceBundleKind is what a run did: wrote a bundle, or read one back.

const (
	// BundleExport writes a workspace to the bucket as a portable bundle.
	BundleExport WorkspaceBundleKind = "export"
	// BundleRestore rebuilds a workspace from one.
	BundleRestore WorkspaceBundleKind = "restore"
)

type WorkspaceInvitation

type WorkspaceInvitation struct {
	ID          uint             `json:"id" gorm:"primaryKey"`
	WorkspaceID uint             `json:"workspace_id" gorm:"index;not null"`
	Email       string           `json:"email" gorm:"not null;index"`
	Role        WorkspaceRole    `json:"role" gorm:"not null;default:viewer"`
	TokenHash   string           `json:"-" gorm:"uniqueIndex;not null"`
	Status      InvitationStatus `json:"status" gorm:"not null;default:pending"`
	InvitedBy   uint             `json:"invited_by" gorm:"not null"`
	ExpiresAt   time.Time        `json:"expires_at" gorm:"not null"`
	CreatedAt   time.Time        `json:"created_at"`
}

WorkspaceInvitation is a pending invite for an email to join a workspace.

type WorkspaceKey

type WorkspaceKey struct {
	ID          uint `json:"id" gorm:"primaryKey"`
	WorkspaceID uint `json:"workspace_id" gorm:"index:idx_wskey_ws_ver,unique;not null"`
	Version     int  `json:"version" gorm:"index:idx_wskey_ws_ver,unique;not null"`
	// WrappedDEK is the DEK encrypted (AES-GCM) under the master KEK — i.e.
	// crypto.Encrypt(base64(dek)). Never returned by the API.
	WrappedDEK string `json:"-" gorm:"type:text;not null"`
	// Active marks the version new writes encrypt with. Older versions are kept so
	// existing ciphertext stays decryptable until a rotation sweep migrates it.
	Active bool `json:"active" gorm:"not null;default:true;index"`

	CreatedAt time.Time `json:"created_at"`
	RotatedAt time.Time `json:"rotated_at"`
}

WorkspaceKey is a workspace's data-encryption key (DEK), stored wrapped by the master KEK. The DEK encrypts the workspace's secrets at rest; the KEK only wraps the DEK. Rotation adds a new active version and re-encrypts to it. Exactly one version per workspace is Active.

type WorkspaceMember

type WorkspaceMember struct {
	ID          uint          `json:"id" gorm:"primaryKey"`
	WorkspaceID uint          `json:"workspace_id" gorm:"uniqueIndex:idx_workspace_user;not null"`
	UserID      uint          `json:"user_id" gorm:"uniqueIndex:idx_workspace_user;not null"`
	Role        WorkspaceRole `json:"role" gorm:"not null;default:viewer"`
	// CustomRoleID, when set, overrides Role with an admin-defined permission set
	// (Enterprise). Role still holds the custom role's BaseRole for rank checks.
	CustomRoleID *uint     `json:"custom_role_id" gorm:"index"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`

	User User `json:"user" gorm:"foreignKey:UserID"`
}

WorkspaceMember links a user to a workspace with a role.

type WorkspaceQuota

type WorkspaceQuota struct {
	WorkspaceID               uint           `json:"workspace_id" gorm:"primaryKey"`
	MaxApps                   *int           `json:"max_apps,omitempty"`
	MaxDatabaseInstances      *int           `json:"max_database_instances,omitempty"`
	MaxCronJobs               *int           `json:"max_cron_jobs,omitempty"`
	MaxVolumes                *int           `json:"max_volumes,omitempty"`
	MaxNetworks               *int           `json:"max_networks,omitempty"`
	MaxAPIKeys                *int           `json:"max_api_keys,omitempty"`
	MaxMembers                *int           `json:"max_members,omitempty"`
	MaxDatabasesPerInstance   *int           `json:"max_databases_per_instance,omitempty"`
	MaxCPUCores               *int           `json:"max_cpu_cores,omitempty"`
	MaxMemoryMB               *int           `json:"max_memory_mb,omitempty"`
	MaxDatabaseInstanceSizeMB *int           `json:"max_database_instance_size_mb,omitempty"`
	MaxStorageMB              *int           `json:"max_storage_mb,omitempty"`
	MaxRunners                *int           `json:"max_runners,omitempty"`
	MaxGPUs                   *int           `json:"max_gpus,omitempty"`
	MaxDatabaseCPUCores       *int           `json:"max_database_cpu_cores,omitempty"`
	MaxDatabaseMemoryMB       *int           `json:"max_database_memory_mb,omitempty"`
	AllowCustomTLS            *bool          `json:"allow_custom_tls,omitempty"`
	AllowPrivilegedHostMounts *bool          `json:"allow_privileged_host_mounts,omitempty"`
	AllowShellExec            *bool          `json:"allow_shell_exec,omitempty"`
	AllowSharedStorage        *bool          `json:"allow_shared_storage,omitempty"`
	AllowDNSProviders         *bool          `json:"allow_dns_providers,omitempty"`
	AllowCustomLabels         *bool          `json:"allow_custom_labels,omitempty"`
	AllowPlatformRunners      *bool          `json:"allow_platform_runners,omitempty"`
	AllowCustomBuilder        *bool          `json:"allow_custom_builder,omitempty"`
	AllowGPU                  *bool          `json:"allow_gpu,omitempty"`
	SecurityProfile           *string        `json:"security_profile,omitempty"`                                // nil = inherit plan
	AllowOfficialImageUser    *bool          `json:"allow_official_image_user,omitempty"`                       // nil = inherit plan
	Placement                 *PlanPlacement `json:"placement,omitempty" gorm:"type:text;serializer:json"`      // nil = inherit plan
	DatabaseSizes             *[]uint        `json:"database_sizes,omitempty" gorm:"type:text;serializer:json"` // nil = inherit plan
	StorageClasses            *[]string      `json:"storage_classes,omitempty" gorm:"type:text;serializer:json"`
	DefaultStorageClass       *string        `json:"default_storage_class,omitempty"`

	UpdatedAt time.Time `json:"updated_at"`
}

WorkspaceQuota holds per-workspace overrides applied on top of the assigned plan. Any non-nil field overrides the plan for that workspace; nil inherits.

type WorkspaceRole

type WorkspaceRole string

WorkspaceRole is a member's role within a workspace.

const (
	WorkspaceRoleOwner     WorkspaceRole = "owner"
	WorkspaceRoleAdmin     WorkspaceRole = "admin"
	WorkspaceRoleDeveloper WorkspaceRole = "developer"
	WorkspaceRoleViewer    WorkspaceRole = "viewer"
)

func (WorkspaceRole) AtLeast

func (r WorkspaceRole) AtLeast(min WorkspaceRole) bool

AtLeast reports whether r is at least as privileged as min.

func (WorkspaceRole) Rank

func (r WorkspaceRole) Rank() int

Rank returns the privilege level of a role (0 if unknown).

func (WorkspaceRole) Valid

func (r WorkspaceRole) Valid() bool

Valid reports whether r is a known role.

type WorkspaceWithRole

type WorkspaceWithRole struct {
	Workspace
	Role WorkspaceRole `json:"role"`
}

WorkspaceWithRole is a workspace annotated with the requesting user's role in it. Returned by the list endpoint so the UI can render role badges and gate admin-only affordances without an extra round-trip per workspace.

Jump to

Keyboard shortcuts

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