models

package
v0.0.18 Latest Latest
Warning

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

Go to latest
Published: May 23, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package models contains database models and related utility functions

Index

Constants

View Source
const (
	InstanceIDField        = "id"
	InstanceCreatedAtField = "created_at"
	InstanceDeletedField   = "deleted"
	InstanceStatusField    = "status"
	InstancePublicIPField  = "public_ip"
	InstanceNameField      = "name"
)

Field names for instance model

View Source
const (
	// DefaultLimit is the max number of rows that are retrieved from the DB per listing API call
	DefaultLimit = 50
	// DBBatchSize is the standard batch size for DB CreateBatch operations
	DBBatchSize = 100
)
View Source
const (
	// TaskStatusField is the field name for task status
	TaskStatusField = "status"
	// TaskIDField is the field name for task ID
	TaskIDField = "id"
	// TaskCreatedAtField is the field name for task created at
	TaskCreatedAtField = "created_at"
	// TaskLockedAtField is the field name for task locked at
	TaskLockedAtField = "locked_at"
	// TaskLockExpiryField is the field name for task lock expiry
	TaskLockExpiryField = "lock_expiry"
	// TaskAttemptsField is the field name for task attempts
	TaskAttemptsField = "attempts"
	// TaskLogsField is the field name for task logs
	TaskLogsField = "logs"
	// TaskErrorField is the field name for task error
	TaskErrorField = "error"
	// TaskPriorityField is the field name for task priority
	TaskPriorityField = "priority"

	// WebhookTimeoutSeconds is the timeout for webhook requests in seconds
	WebhookTimeout = 10 * time.Second
	// WebhookContentType is the content type for webhook requests
	WebhookContentType = "application/json"

	// TaskLockTimeout is the duration after which a task lock is considered expired
	TaskLockTimeout = 5 * time.Minute
)

Field names for task model

View Source
const AdminID uint = math.MaxUint32

AdminID represents the special ID for admin-level access

Variables

This section is empty.

Functions

func ValidateOwnerID

func ValidateOwnerID(ownerID uint) error

ValidateOwnerID ensures the ownerID is valid

Types

type Instance

type Instance struct {
	gorm.Model
	OwnerID            uint           `json:"owner_id" gorm:"not null;index"`
	ProjectID          uint           `json:"project_id" gorm:"not null;index"`
	Name               string         `json:"name" gorm:"varchar(255);index"`
	ProviderID         ProviderID     `json:"provider_id" gorm:"not null"`
	ProviderInstanceID int            `json:"provider_instance_id" gorm:"not null"`
	PublicIP           string         `json:"public_ip" gorm:"varchar(100)"`
	Region             string         `json:"region" gorm:"varchar(255)"`
	Size               string         `json:"size" gorm:"varchar(255)"`
	Image              string         `json:"image" gorm:"varchar(255)"`
	Tags               pq.StringArray `json:"tags" gorm:"type:text[]"`
	Status             InstanceStatus `json:"status" gorm:"index"`
	VolumeIDs          pq.StringArray `json:"volume_ids" gorm:"type:text[]"`
	VolumeDetails      VolumeDetails  `json:"volume_details" gorm:"type:jsonb"`
	CreatedAt          time.Time      `json:"created_at" gorm:"index"`
	PayloadStatus      PayloadStatus  `json:"payload_status" gorm:"default:0;index"` // Default to PayloadStatusNone
}

Instance represents a compute instance in the system

func (Instance) MarshalJSON

func (i Instance) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Instance

type InstanceStatus

type InstanceStatus int

InstanceStatus represents the current state of an instance

const (
	// InstanceStatusUnknown represents an unknown or invalid instance status
	InstanceStatusUnknown InstanceStatus = iota
	// InstanceStatusPending indicates the instance is being created
	InstanceStatusPending
	// InstanceStatusCreated indicates the instance has been created but not provisioned
	InstanceStatusCreated
	// InstanceStatusProvisioning indicates the instance is being provisioned
	InstanceStatusProvisioning
	// InstanceStatusReady indicates the instance is operational
	InstanceStatusReady
	// InstanceStatusTerminated indicates the instance is terminated
	InstanceStatusTerminated
)

Instance status constants

func ParseInstanceStatus

func ParseInstanceStatus(str string) (InstanceStatus, error)

ParseInstanceStatus converts a string representation of an instance status to InstanceStatus type

func (InstanceStatus) MarshalJSON

func (s InstanceStatus) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for InstanceStatus

func (InstanceStatus) String

func (s InstanceStatus) String() string

func (*InstanceStatus) UnmarshalJSON

func (s *InstanceStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for InstanceStatus

type ListOptions

type ListOptions struct {
	// Pagination
	Limit  int `json:"limit"`  // Number of items to return
	Offset int `json:"offset"` // Number of items to skip
	// Filtering
	IncludeDeleted bool         `json:"include_deleted"`
	StatusFilter   StatusFilter `json:"status_filter,omitempty"` // How to filter by status
	// Statuses
	InstanceStatus *InstanceStatus `json:"instance_status,omitempty"` // Filter by instance status
}

ListOptions represents pagination and filtering options for list operations

type PayloadStatus

type PayloadStatus int

PayloadStatus represents the state of a payload operation on an instance

const (
	// PayloadStatusNone indicates no payload operation has been initiated
	PayloadStatusNone PayloadStatus = iota
	// PayloadStatusPendingCopy indicates the payload is waiting to be copied
	PayloadStatusPendingCopy
	// PayloadStatusCopyFailed indicates the payload copy operation failed
	PayloadStatusCopyFailed
	// PayloadStatusCopied indicates the payload has been successfully copied
	PayloadStatusCopied
	// PayloadStatusPendingExecution indicates the payload is waiting to be executed
	PayloadStatusPendingExecution
	// PayloadStatusExecutionFailed indicates the payload execution failed
	PayloadStatusExecutionFailed
	// PayloadStatusExecuted indicates the payload was executed successfully
	PayloadStatusExecuted
)

Payload status constants

func ParsePayloadStatus

func ParsePayloadStatus(str string) (PayloadStatus, error)

ParsePayloadStatus converts a string representation to PayloadStatus type

func (PayloadStatus) MarshalJSON

func (ps PayloadStatus) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for PayloadStatus

func (PayloadStatus) String

func (ps PayloadStatus) String() string

String returns the string representation of PayloadStatus

func (*PayloadStatus) UnmarshalJSON

func (ps *PayloadStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for PayloadStatus

type Project

type Project struct {
	gorm.Model
	OwnerID     uint      `json:"-" gorm:"not null; index"`
	Name        string    `json:"name" gorm:"not null; index; unique"`
	Description string    `json:"description" gorm:"type:text"`
	Config      string    `json:"config" gorm:"type:text"`
	Tasks       []Task    `json:"tasks" gorm:"foreignKey:ProjectID"`
	CreatedAt   time.Time `json:"created_at" gorm:"index"`
}

Project represents a collection of related tasks and instances

func (Project) MarshalJSON

func (p Project) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Project

type ProviderID

type ProviderID string

ProviderID represents a unique identifier for a cloud provider

const (
	// ProviderAWS represents Amazon Web Services provider
	ProviderAWS ProviderID = "aws"
	// ProviderGCP represents Google Cloud Platform provider
	ProviderGCP ProviderID = "gcp"
	// ProviderAzure represents Microsoft Azure provider
	ProviderAzure ProviderID = "azure"
	// ProviderDO represents DigitalOcean provider
	ProviderDO ProviderID = "do"
	// ProviderScaleway represents Scaleway provider
	ProviderScaleway ProviderID = "scw"
	// ProviderVultr represents Vultr provider
	ProviderVultr ProviderID = "vultr"
	// ProviderLinode represents Linode provider
	ProviderLinode ProviderID = "linode"
	// ProviderHetzner represents Hetzner provider
	ProviderHetzner ProviderID = "hetzner"
	// ProviderOVH represents OVH provider
	ProviderOVH ProviderID = "ovh"
	// ProviderXimera represents Ximera provider
	ProviderXimera ProviderID = "ximera"

	// Mock Providers
	// ProviderDOMock1 represents DigitalOcean provider mock 1
	ProviderDOMock1 ProviderID = "do-mock"
	// ProviderDOMock2 represents DigitalOcean provider mock 2
	ProviderDOMock2 ProviderID = "digitalocean-mock"
	// ProviderDOMock3 represents a mock provider
	ProviderMock3 ProviderID = "mock"
)

Provider constants define the supported cloud providers

func FromString

func FromString(s string) ProviderID

FromString creates a ProviderID from a string

func ToProviderID

func ToProviderID(s string) ProviderID

ToProviderID converts a string to a ProviderID

func (ProviderID) IsValid

func (p ProviderID) IsValid() bool

IsValid checks if the provider ID is a valid supported provider

func (ProviderID) MarshalJSON

func (p ProviderID) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

func (ProviderID) String

func (p ProviderID) String() string

String implements the fmt.Stringer interface

func (*ProviderID) UnmarshalJSON

func (p *ProviderID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

type StatusFilter

type StatusFilter string

StatusFilter represents how to filter db items by status

const (
	// StatusFilterEqual indicates filtering for instances with matching status
	StatusFilterEqual StatusFilter = "equal"
	// StatusFilterNotEqual indicates filtering for instances with non-matching status
	StatusFilterNotEqual StatusFilter = "not_equal"
)

type Task

type Task struct {
	gorm.Model
	ProjectID   uint            `json:"project_id" gorm:"not null; index"`
	OwnerID     uint            `json:"-" gorm:"not null; index"`
	InstanceID  uint            `json:"instance_id,omitempty" gorm:"index"` // Link to the specific instance, if applicable
	Action      TaskAction      `json:"action" gorm:"type:varchar(32)"`     // make sure this is long enough to handle all actions
	Status      TaskStatus      `json:"status" gorm:"not null; index"`
	Payload     json.RawMessage `json:"payload,omitempty" gorm:"type:jsonb"` // Data that is required for the task to be executed
	Result      json.RawMessage `json:"result,omitempty" gorm:"type:jsonb"`  // Result of the task
	Attempts    uint            `json:"attempts" gorm:"not null; default:0"`
	Logs        string          `json:"logs,omitempty" gorm:"type:text"`
	Error       string          `json:"error,omitempty" gorm:"type:text"`
	WebhookURL  string          `json:"webhook_url,omitempty" gorm:"type:text"`
	WebhookSent bool            `json:"webhook_sent" gorm:"not null;default:false;index"`
	CreatedAt   time.Time       `json:"created_at" gorm:"index"`
	LockedAt    *time.Time      `json:"locked_at,omitempty" gorm:"index"`   // When the task was locked for processing
	LockExpiry  *time.Time      `json:"lock_expiry,omitempty" gorm:""`      // When the lock expires
	Priority    TaskPriority    `json:"priority" gorm:"not null;default:1"` // Task priority (higher number = lower priority)
}

Task represents an asynchronous operation that can be tracked

func (*Task) BeforeCreate

func (t *Task) BeforeCreate(_ *gorm.DB) error

BeforeCreate is a GORM hook that runs before creating a new task

func (*Task) IsLocked added in v0.0.9

func (t *Task) IsLocked() bool

IsLocked checks if the task is currently locked for processing

func (*Task) Lock added in v0.0.9

func (t *Task) Lock(duration time.Duration)

Lock locks the task for processing

func (Task) MarshalJSON

func (t Task) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Task

func (*Task) SendWebhook

func (t *Task) SendWebhook() error

SendWebhook sends a notification to the webhook URL if configured

func (*Task) Unlock added in v0.0.9

func (t *Task) Unlock()

Unlock unlocks the task

func (*Task) Validate

func (t *Task) Validate() error

Validate ensures that the task data is valid

type TaskAction

type TaskAction string

TaskAction represents the possible actions a task can perform.

const (
	// TaskActionCreateInstances represents the action to create instances.
	TaskActionCreateInstances TaskAction = "create_instances"
	// TaskActionTerminateInstances represents the action to terminate instances.
	TaskActionTerminateInstances TaskAction = "terminate_instances"
)

type TaskPriority added in v0.0.9

type TaskPriority int

TaskPriority represents the priority level of a task

const (
	// TaskPriorityHigh represents high priority tasks (like create operations)
	TaskPriorityHigh TaskPriority = 1
	// TaskPriorityLow represents low priority tasks (like terminate operations)
	TaskPriorityLow TaskPriority = 2
)

func (TaskPriority) String added in v0.0.9

func (p TaskPriority) String() string

String returns the string representation of the task priority

type TaskStatus

type TaskStatus string

TaskStatus represents the current state of a task

const (
	// TaskStatusUnknown represents an unknown or invalid task status
	TaskStatusUnknown TaskStatus = "unknown"
	// TaskStatusPending indicates the task is waiting to be processed
	TaskStatusPending TaskStatus = "pending"
	// TaskStatusRunning indicates the task is currently being processed
	TaskStatusRunning TaskStatus = "running"
	// TaskStatusCompleted indicates the task has been successfully completed
	TaskStatusCompleted TaskStatus = "completed"
	// TaskStatusFailed indicates the task has failed
	TaskStatusFailed TaskStatus = "failed"
	// TaskStatusTerminated indicates the task was manually aborted
	TaskStatusTerminated TaskStatus = "terminated"
)

Task status constants

func ParseTaskStatus

func ParseTaskStatus(str string) (TaskStatus, error)

ParseTaskStatus converts a string to a TaskStatus type

func (*TaskStatus) MarshalJSON

func (s *TaskStatus) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for TaskStatus

func (TaskStatus) String

func (s TaskStatus) String() string

String returns the string representation of the task status

func (*TaskStatus) UnmarshalJSON

func (s *TaskStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for TaskStatus

type User

type User struct {
	gorm.Model
	Username     string   `json:"username" gorm:"not null;unique"`
	Email        string   `json:"email" gorm:""`
	Role         UserRole `json:"role" gorm:"index"`
	PublicSSHKey string   `json:"public_ssh_key" gorm:""`
	CreatedAt    string   `json:"created_at" gorm:""`
	UpdatedAt    string   `json:"updated_at" gorm:""`
}

User represents a user in the system

func (User) MarshalJSON

func (u User) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for User

type UserQueryOptions

type UserQueryOptions struct {
	Username string `json:"username" gorm:"not null;unique"`
}

UserQueryOptions represents query params for GetUserByUsername operation

type UserRole

type UserRole int

UserRole represents the role of a user in the system

const (
	// UserRoleUser represents a standard user
	UserRoleUser UserRole = iota
	// UserRoleAdmin represents an administrator user
	UserRoleAdmin
)

User role constants

func ParseUserRole

func ParseUserRole(str string) (UserRole, error)

ParseUserRole converts a string representation of a user role to UserRole type

func (UserRole) String

func (s UserRole) String() string

type VolumeDetail

type VolumeDetail struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	Region     string `json:"region"`
	SizeGB     int    `json:"size_gb"`
	MountPoint string `json:"mount_point"`
}

VolumeDetail represents the details of a volume attached to an instance

type VolumeDetails

type VolumeDetails []VolumeDetail

VolumeDetails is a slice of VolumeDetail

func (*VolumeDetails) Scan

func (vd *VolumeDetails) Scan(value interface{}) error

Scan implements the sql.Scanner interface

func (VolumeDetails) Value

func (vd VolumeDetails) Value() (driver.Value, error)

Value implements the driver.Valuer interface

Jump to

Keyboard shortcuts

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