utils

package
v0.2.15 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2025 License: MIT Imports: 53 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxImageSize         = 4 * 1024 * 1024 // 4MB
	MaxAppNameLength     = 100
	MaxDescriptionLength = 1000
	BytesPerMB           = 1024 * 1024
)
View Source
const (
	KMSEncryptionPublicKeyPath  = "keys/%s/kms-encryption-public-key.pem"
	KMSSigningPublicKeyPath     = "keys/%s/kms-signing-public-key.pem"
	KMSClientPath               = "tools/kms-client"
	LayeredDockerfilePath       = "internal/templates/docker/Dockerfile.layered.tmpl"
	EnvSourceScriptTemplatePath = "internal/templates/scripts/compute-source-env.sh.tmpl"
	JWTFilePath                 = "/run/container_launcher/attestation_verifier_claims_token"

	// Build-related constants
	TempImagePrefix       = "eigenx-temp-"
	LayeredBuildDirPrefix = "eigenx-layered-build"
	LayeredDockerfileName = "Dockerfile.eigencompute"
	EnvSourceScriptName   = "compute-source-env.sh"
	KMSClientBinaryName   = "kms-client"
	KMSEncryptionKeyName  = "kms-encryption-public-key.pem"
	KMSSigningKeyName     = "kms-signing-public-key.pem"
	TlsKeygenBinaryName   = "tls-keygen"
	CaddyfileName         = "Caddyfile"
	DockerPlatform        = "linux/amd64"
	LinuxOS               = "linux"
	AMD64Arch             = "amd64"
	SHA256Prefix          = "sha256:"

	RegistryPropagationWaitSeconds = 3
)
View Source
const (
	MaxAddressCount   = 5  // Max addresses to return per app
	MaxAppsPerRequest = 10 // Max apps allowed per API request
)

Variables

View Source
var (
	ValidImageExtensions = []string{".jpg", ".jpeg", ".png"}
	ValidXHosts          = []string{"twitter.com", "www.twitter.com", "x.com", "www.x.com"}
)

Functions

func CalculateAndSignApiPermissionDigest

func CalculateAndSignApiPermissionDigest(
	cCtx *cli.Context,
	permission [4]byte,
	expiry *big.Int,
) ([]byte, error)

CalculateAndSignApiPermissionDigest calculates the API permission digest using the contract and signs it with the user's private key

func CheckAppLogPermission

func CheckAppLogPermission(cCtx *cli.Context, appAddress ethcommon.Address) (bool, error)

CheckAppLogPermission checks if an app currently has public log viewing permissions

func ConfirmMainnetEnvironment

func ConfirmMainnetEnvironment(env string) error

ConfirmMainnetEnvironment shows a confirmation prompt for mainnet environments

func ExtractAndFindAvailableName added in v0.2.14

func ExtractAndFindAvailableName(cCtx *cli.Context, context, imageRef string) (string, error)

ExtractAndFindAvailableName extracts a base name from imageRef and finds an available variant

func GenerateAuthHeaders

func GenerateAuthHeaders(
	cCtx *cli.Context,
	permission [4]byte,
	expiry *big.Int,
) (map[string]string, error)

GenerateAuthHeaders generates Authorization and X-eigenx-expiry headers for API authentication by using the contract to calculate and sign the permission digest

func GetAndPrintAppInfo

func GetAndPrintAppInfo(cCtx *cli.Context, appID ethcommon.Address, statusOverride ...string) error

func GetAppControllerBinding

func GetAppControllerBinding(cCtx *cli.Context) (*ethclient.Client, *AppController.AppController, error)

func GetAppDescriptionInteractive added in v0.2.14

func GetAppDescriptionInteractive(cCtx *cli.Context) (*string, error)

func GetAppIDInteractive

func GetAppIDInteractive(cCtx *cli.Context, resolver *AppResolver, argIndex int, action string) (ethcommon.Address, error)

GetAppIDInteractive gets app ID from args or interactive selection If resolver is provided, uses it to avoid duplicate API calls. If resolver is nil, creates a new one.

func GetAppImageInteractive added in v0.2.14

func GetAppImageInteractive(cCtx *cli.Context) (string, error)

func GetAppNameInteractive added in v0.2.14

func GetAppNameInteractive(cCtx *cli.Context, defaultName string) (string, error)

func GetAppWebsiteInteractive added in v0.2.14

func GetAppWebsiteInteractive(cCtx *cli.Context) (*string, error)

func GetAppXURLInteractive added in v0.2.14

func GetAppXURLInteractive(cCtx *cli.Context) (*string, error)

func GetContractCaller

func GetContractCaller(cCtx *cli.Context) (*common.ContractCaller, error)

GetContractCaller creates a contract caller from the CLI context

func GetDeveloperAddress

func GetDeveloperAddress(cCtx *cli.Context) (ethcommon.Address, error)

GetDeveloperAddress gets developer address from private key

func GetDockerfileInteractive

func GetDockerfileInteractive(cCtx *cli.Context) (string, error)

GetDockerfileInteractive prompts to build from Dockerfile if it exists

func GetEnvFileInteractive

func GetEnvFileInteractive(cCtx *cli.Context) (string, error)

GetEnvFileInteractive prompts for env file path if not provided

func GetEnvironmentConfig

func GetEnvironmentConfig(cCtx *cli.Context) (common.EnvironmentConfig, error)

func GetEnvironmentDescription

func GetEnvironmentDescription(name, fallback string, withPrefix bool) string

GetEnvironmentDescription returns a human-readable description for an environment

func GetEnvironmentInteractive

func GetEnvironmentInteractive(cCtx *cli.Context, argIndex int) (string, error)

GetEnvironmentInteractive gets environment from args or interactive selection

func GetImageReferenceInteractive

func GetImageReferenceInteractive(cCtx *cli.Context, argIndex int, buildFromDockerfile bool) (string, error)

GetImageReferenceInteractive prompts for image reference if not provided

func GetInstanceTypeInteractive added in v0.2.8

func GetInstanceTypeInteractive(cCtx *cli.Context, defaultSKU string) (string, error)

GetInstanceTypeInteractive prompts for instance type if not provided via flag. The defaultSKU parameter is used as the default selection in interactive mode: - For new deployments: pass empty string (uses first SKU from backend) - For upgrades: pass current app's instance type

func GetLayeredTargetImageInteractive

func GetLayeredTargetImageInteractive(cCtx *cli.Context, sourceImageRef string) (string, error)

GetLayeredTargetImageInteractive prompts for target image when layering a published image

func GetLogSettingsInteractive

func GetLogSettingsInteractive(cCtx *cli.Context) (logRedirect string, publicLogs bool, err error)

GetLogSettingsInteractive gets log redirection and visibility settings from flags or interactive prompt

func GetPrivateKeyOrFail

func GetPrivateKeyOrFail(cCtx *cli.Context) (string, error)

GetPrivateKeyOrFail gets the private key from flag, environment, or keyring, failing with clear instructions if not found

func IsAppNameAvailable

func IsAppNameAvailable(cCtx *cli.Context, resolver *AppResolver, name string) bool

IsAppNameAvailable checks if an app name is available in the given context. If resolver is provided, uses it; otherwise creates a new one.

func IsPushPermissionError

func IsPushPermissionError(err error) bool

IsPushPermissionError checks if an error is a push permission error

func PrepareReleaseFromContext

func PrepareReleaseFromContext(cCtx *cli.Context, environmentConfig *common.EnvironmentConfig, appID gethcommon.Address, dockerfilePath string, imageRef string, envFilePath string, logRedirect string, instanceType string, maxPushRetries int) (appcontrollerV2.IAppControllerRelease, string, error)

PrepareReleaseFromContext prepares a release with separated Dockerfile handling The dockerfile path and env file path are provided as parameters (already collected earlier) maxPushRetries controls how many times to retry on push permission errors (0 = no retries)

func PrintAppInfo

func PrintAppInfo(ctx context.Context, logger iface.Logger, client *ethclient.Client, appID ethcommon.Address, config AppController.IAppControllerAppConfig, info AppInfo, environmentName string) error

func PrintAppInfoWithStatus

func PrintAppInfoWithStatus(ctx context.Context, logger iface.Logger, client *ethclient.Client, appID ethcommon.Address, config AppController.IAppControllerAppConfig, info AppInfo, environmentName string, statusOverride string) error

func SanitizeString added in v0.2.14

func SanitizeString(s string) string

SanitizeString sanitizes a string by trimming whitespace and escaping HTML

func SanitizeURL added in v0.2.14

func SanitizeURL(rawURL string) (string, error)

SanitizeURL sanitizes a URL by trimming whitespace and validating

func SanitizeXURL added in v0.2.14

func SanitizeXURL(rawURL string) (string, error)

SanitizeXURL sanitizes an X URL

func SelectRegistryInteractive

func SelectRegistryInteractive(registries []registryInfo, imageName string, tag string, promptMessage string, validator func(string) error) (string, error)

SelectRegistryInteractive provides interactive selection of registry for image reference

func SelectTemplateInteractive added in v0.2.12

func SelectTemplateInteractive(language string) (string, error)

SelectTemplateInteractive prompts the user to select a template from the catalog

func ShowCountdown added in v0.2.5

func ShowCountdown(ctx context.Context, seconds int)

ShowCountdown displays a countdown timer with gray text

func ValidateAppDescription added in v0.2.14

func ValidateAppDescription(description string) error

ValidateAppDescription validates an app description

func ValidateAppName added in v0.2.14

func ValidateAppName(name string) error

ValidateAppName validates an app name

func ValidateURL added in v0.2.14

func ValidateURL(rawURL string) error

ValidateURL validates that a string is a valid URL

func ValidateXURL added in v0.2.14

func ValidateXURL(rawURL string) error

ValidateXURL validates that a URL is a valid X (Twitter) URL

func WatchAppInfoLoop added in v0.2.5

func WatchAppInfoLoop(cCtx *cli.Context, appID ethcommon.Address, stopCondition func(string, string) (bool, error), notifyOnStates []string, statusOverride ...string) error

WatchAppInfoLoop is the shared watch logic for monitoring app status changes stopCondition is called with (status, ip) and returns (shouldStop, error) If stopCondition is nil, watches indefinitely notifyOnStates: if provided, only print status changes when transitioning TO these states statusOverride: if provided, overrides the initial status display for user clarity

func WatchUntilTransitionComplete added in v0.2.12

func WatchUntilTransitionComplete(cCtx *cli.Context, appID ethcommon.Address, statusOverride ...string) error

WatchUntilTransitionComplete watches app info until operation completes (deploy, upgrade, start, stop) statusOverride: if provided, indicates the operation type (e.g., "Deploying", "Upgrading", "Resuming", "Stopping")

Types

type AppInfo

type AppInfo struct {
	EVMAddresses    []kmstypes.EVMAddressAndDerivationPath
	SolanaAddresses []kmstypes.SolanaAddressAndDerivationPath
	Status          string
	Ip              string
	MachineType     string
	Profile         *AppProfileResponse
}

AppInfo contains the app info with parsed and validated addresses

type AppInfoResponse

type AppInfoResponse struct {
	Apps []AppInfo
}

type AppProfile added in v0.2.14

type AppProfile struct {
	Name        string `json:"name"`
	Website     string `json:"website"`
	Description string `json:"description"`
	XURL        string `json:"xURL"`
	ImageURL    string `json:"imageURL"`
}

AppProfile represents the profile information for an app

type AppProfileResponse added in v0.2.14

type AppProfileResponse struct {
	Name        string  `json:"name"`
	Website     *string `json:"website,omitempty"`
	Description *string `json:"description,omitempty"`
	XURL        *string `json:"xURL,omitempty"`
	ImageURL    *string `json:"imageURL,omitempty"`
}

type AppResolver added in v0.2.15

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

AppResolver provides centralized app name/ID resolution with caching. It checks remote profile names first, then falls back to local registry (legacy).

func NewAppResolver added in v0.2.15

func NewAppResolver(cCtx *cli.Context) (*AppResolver, error)

NewAppResolver creates a new resolver instance for the current environment

func (*AppResolver) FindAvailableName added in v0.2.15

func (r *AppResolver) FindAvailableName(baseName string) string

FindAvailableName finds an available variant of the base name by appending numbers

func (*AppResolver) FormatAppDisplay added in v0.2.15

func (r *AppResolver) FormatAppDisplay(appID ethcommon.Address) string

FormatAppDisplay returns a user-friendly display string for an app Returns "name (0x123...)" if name exists, or just "0x123..." if no name Checks remote profile first, then falls back to local registry

func (*AppResolver) GetAllApps added in v0.2.15

func (r *AppResolver) GetAllApps() ([]ethcommon.Address, error)

GetAllApps returns the cached list of app addresses

func (*AppResolver) GetAppName added in v0.2.15

func (r *AppResolver) GetAppName(appID ethcommon.Address) string

GetAppName returns the app name by checking remote profile first, then falling back to local registry

func (*AppResolver) IsNameAvailable added in v0.2.15

func (r *AppResolver) IsNameAvailable(name string) bool

IsNameAvailable checks if a name is available by checking both remote profiles and local registry

func (*AppResolver) ResolveAppID added in v0.2.15

func (r *AppResolver) ResolveAppID(nameOrID string) (ethcommon.Address, error)

ResolveAppID resolves an app ID or name by checking remote profile names first, then falling back to the local registry (legacy)

type AppStatus

type AppStatus struct {
	Status string `json:"app_status"`
}

type AppStatusResponse

type AppStatusResponse struct {
	Apps []AppStatus `json:"apps"`
}

type CheckoutSessionResponse added in v0.2.12

type CheckoutSessionResponse struct {
	CheckoutURL string `json:"checkout_url"`
}

type CollectedProfile added in v0.2.14

type CollectedProfile struct {
	Name        string
	Website     *string
	Description *string
	XURL        *string
	ImagePath   string
}

CollectedProfile holds collected profile information with pointer fields for optional values

func GetAppProfileInteractive added in v0.2.14

func GetAppProfileInteractive(cCtx *cli.Context, defaultName string, allowRetry bool) (*CollectedProfile, error)

GetAppProfileInteractive collects app profile information interactively If defaultName is provided, it will be used as the suggested name If allowRetry is true, user can re-enter information on rejection (deploy flow) If allowRetry is false, rejection returns an error (profile set flow) Returns CollectedProfile with at least a name (required), and optional fields

type EnvSourceScriptTemplateData

type EnvSourceScriptTemplateData struct {
	KMSServerURL string
	UserAPIURL   string
}

type ImageInfo added in v0.2.14

type ImageInfo struct {
	Width  int
	Height int
	SizeKB float64
	Format string
}

ImageInfo contains validated image metadata

func ValidateAndGetImageInfo added in v0.2.14

func ValidateAndGetImageInfo(filePath string) (string, *ImageInfo, error)

ValidateAndGetImageInfo validates and extracts image information in one pass Returns the cleaned file path (with quotes stripped) along with image info

func (*ImageInfo) AspectRatio added in v0.2.14

func (img *ImageInfo) AspectRatio() float64

AspectRatio returns the width/height ratio

func (*ImageInfo) IsSquare added in v0.2.14

func (img *ImageInfo) IsSquare() bool

IsSquare checks if image has approximately square aspect ratio

type InstanceType added in v0.2.8

type InstanceType struct {
	SKU         string `json:"sku"`         // SKU value (e.g., "g1-standard-4t")
	Description string `json:"description"` // Human-readable description (e.g., "4 vCPUs, 16 GB memory, TDX")
}

InstanceType represents a machine instance type configuration. This struct matches the backend API response format for SKUs.

type LayeredDockerfileTemplateData

type LayeredDockerfileTemplateData struct {
	BaseImage        string
	OriginalCmd      string
	OriginalUser     string
	LogRedirect      string
	IncludeTLS       bool
	EigenXCLIVersion string
}

type Platform

type Platform struct {
	OS   string
	Arch string
}

Platform represents a container platform

func (Platform) IsLinuxAMD64

func (p Platform) IsLinuxAMD64() bool

IsLinuxAMD64 checks if platform matches required linux/amd64

func (Platform) String

func (p Platform) String() string

String returns the platform in standard format

type PreflightContext

type PreflightContext struct {
	Caller            *common.ContractCaller
	EnvironmentConfig *common.EnvironmentConfig
	Client            *ethclient.Client
	Resolver          *AppResolver
	PrivateKey        string
}

PreflightContext contains validated context needed for contract operations

func DoPreflightChecks

func DoPreflightChecks(cCtx *cli.Context) (*PreflightContext, error)

DoPreflightChecks performs early validation of authentication and network connectivity This should be called at the beginning of any command that requires contract interaction

type PromptConfig added in v0.2.14

type PromptConfig struct {
	FlagName    string
	Prompt      string
	Placeholder string
	Default     string // Optional default value to suggest to user
	Validate    func(string) error
	Sanitize    func(string) (string, error)
}

PromptConfig contains configuration for the flag-or-prompt pattern

type PushPermissionError

type PushPermissionError struct {
	ImageRef string
	Err      error
}

PushPermissionError indicates a push failed due to authentication/permission issues

func (*PushPermissionError) Error

func (e *PushPermissionError) Error() string

func (*PushPermissionError) Unwrap

func (e *PushPermissionError) Unwrap() error

type RawAppInfo added in v0.2.12

type RawAppInfo struct {
	Addresses   json.RawMessage     `json:"addresses"`
	Status      string              `json:"app_status"`
	Ip          string              `json:"ip"`
	MachineType string              `json:"machine_type"`
	Profile     *AppProfileResponse `json:"profile,omitempty"`
}

type RawAppInfoResponse added in v0.2.12

type RawAppInfoResponse struct {
	Apps []RawAppInfo `json:"apps"`
}

type SKUListResponse added in v0.2.8

type SKUListResponse struct {
	SKUs []InstanceType `json:"skus"`
}

type SubscriptionStatus added in v0.2.12

type SubscriptionStatus string

SubscriptionStatus represents the state of a user's subscription

const (
	StatusIncomplete        SubscriptionStatus = "incomplete"
	StatusIncompleteExpired SubscriptionStatus = "incomplete_expired"
	StatusTrialing          SubscriptionStatus = "trialing"
	StatusActive            SubscriptionStatus = "active"
	StatusPastDue           SubscriptionStatus = "past_due"
	StatusCanceled          SubscriptionStatus = "canceled"
	StatusUnpaid            SubscriptionStatus = "unpaid"
	StatusPaused            SubscriptionStatus = "paused"
	StatusInactive          SubscriptionStatus = "inactive"
)

type UpcomingInvoice added in v0.2.12

type UpcomingInvoice struct {
	Amount      float64 `json:"amount"`
	Date        int64   `json:"date"`
	Description string  `json:"description"`
}

type UserApiClient

type UserApiClient struct {
	Client *http.Client
	// contains filtered or unexported fields
}

func NewUserApiClient

func NewUserApiClient(cCtx *cli.Context) (*UserApiClient, error)

func (*UserApiClient) CancelSubscription added in v0.2.12

func (cc *UserApiClient) CancelSubscription(cCtx *cli.Context) error

func (*UserApiClient) CreateCheckoutSession added in v0.2.12

func (cc *UserApiClient) CreateCheckoutSession(cCtx *cli.Context) (*CheckoutSessionResponse, error)

func (*UserApiClient) GetInfos

func (cc *UserApiClient) GetInfos(cCtx *cli.Context, appIDs []ethcommon.Address, addressCount int) (*AppInfoResponse, error)

func (*UserApiClient) GetLogs

func (cc *UserApiClient) GetLogs(cCtx *cli.Context, appID ethcommon.Address) (string, error)

func (*UserApiClient) GetSKUs added in v0.2.8

func (cc *UserApiClient) GetSKUs(cCtx *cli.Context) (*SKUListResponse, error)

func (*UserApiClient) GetStatuses

func (cc *UserApiClient) GetStatuses(cCtx *cli.Context, appIDs []ethcommon.Address) (*AppStatusResponse, error)

func (*UserApiClient) GetUserSubscription added in v0.2.12

func (cc *UserApiClient) GetUserSubscription(cCtx *cli.Context) (*UserSubscriptionResponse, error)

func (*UserApiClient) UploadAppProfile added in v0.2.14

func (cc *UserApiClient) UploadAppProfile(cCtx *cli.Context, appAddress string, name string, website, description, xURL *string, imagePath string) (*AppProfileResponse, error)

UploadAppProfile uploads app profile information with optional image

type UserSubscriptionResponse added in v0.2.12

type UserSubscriptionResponse struct {
	Status             SubscriptionStatus `json:"status"`
	CurrentPeriodStart *int64             `json:"current_period_start,omitempty"`
	CurrentPeriodEnd   *int64             `json:"current_period_end,omitempty"`
	PlanPrice          *float64           `json:"plan_price,omitempty"`
	Currency           *string            `json:"currency,omitempty"`
	UpcomingInvoice    *UpcomingInvoice   `json:"upcoming_invoice,omitempty"`
	CancelAtPeriodEnd  *bool              `json:"cancel_at_period_end,omitempty"`
	CanceledAt         *int64             `json:"canceled_at,omitempty"`
	PortalURL          *string            `json:"portal_url,omitempty"`
}

Jump to

Keyboard shortcuts

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