cloud

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cloud is conch's client of Conch Cloud's control plane: signing a device in (the device flow), keeping its tokens, and the calls a person's conch makes — the account, its devices, its machines and how to reach one (contract conch-cloud/contract, openapi.yaml's userToken side and PROTOCOL.md §3.2).

Nothing here runs unless somebody signed in: Open answers ErrNotSignedIn from what is on disk, without a request, so a conch with no account behaves exactly as one without this package.

Index

Constants

View Source
const (
	StateCreating   = "creating"
	StateRunning    = "running"
	StateSleeping   = "sleeping"
	StateAsleep     = "asleep"
	StateWaking     = "waking"
	StateArchived   = "archived"
	StateError      = "error"
	StateDestroying = "destroying"
)

Machine states (openapi.yaml MachineState). A state this list lacks is passed through as it is.

View Source
const (
	EventMachineState   = "machine.state"
	EventMachineUpdated = "machine.updated"
	EventMachineDeleted = "machine.deleted"
	EventDeviceRevoked  = "device.revoked"
)

Event types a client acts on; others are ignored.

View Source
const (
	ClientCLI    = "cli"
	ClientTUI    = "tui"
	ClientMacApp = "mac_app"
)

Clients a device signs in as (DeviceAuthRequest.client).

View Source
const Contract = "1.4.0"

Contract is the conch-cloud contract version this client speaks, sent as Conch-Contract on every request (PROTOCOL §1).

View Source
const DefaultURL = "https://api.cloud.conch.dev"

DefaultURL is the contract's production server.

View Source
const URLEnv = "CONCH_CLOUD_URL"

URLEnv overrides the API's address: a development server, or a test's.

Variables

View Source
var (
	ErrLoginDenied  = errors.New("the sign-in was denied")
	ErrLoginExpired = errors.New("the code expired before it was approved; run conch login again")
)

ErrLoginDenied and ErrLoginExpired end a sign-in that will not succeed.

View Source
var (
	ErrUnauthorized         = errors.New("unauthorized")
	ErrForbidden            = errors.New("forbidden")
	ErrNotFound             = errors.New("not found")
	ErrInvalidRequest       = errors.New("invalid request")
	ErrAuthorizationPending = errors.New("authorization pending")
	ErrSlowDown             = errors.New("slow down")
	ErrAccessDenied         = errors.New("access denied")
	ErrExpiredToken         = errors.New("expired token")
	ErrPlanLimit            = errors.New("plan limit")
	ErrPaymentRequired      = errors.New("payment required")
	ErrConflict             = errors.New("conflict")
	ErrAgentsWorking        = errors.New("agents working")
	ErrContractUnsupported  = errors.New("contract unsupported")
	ErrRateLimited          = errors.New("rate limited")
	ErrUnavailable          = errors.New("unavailable")
	ErrNoProvider           = errors.New("no provider")
	ErrSuspended            = errors.New("suspended")
)

Errors by the contract's Problem.code, for errors.Is.

View Source
var ErrDropped = errors.New("the connection to the machine dropped")

ErrDropped is a tunnel that ended before its socket did: the relay or the machine went away mid-stream.

View Source
var ErrNotSignedIn = errors.New("not signed in to Conch Cloud (run: conch login)")

ErrNotSignedIn is a conch with no Conch Cloud account. It is said from what is on disk; nothing was asked of the network.

View Source
var ErrSignedOut = errors.New("this device was signed out of Conch Cloud (run: conch login)")

ErrSignedOut is a sign-in the control plane no longer takes — the refresh token was revoked, expired or reused, or the device was removed — so this conch forgot it.

Functions

func APIURL

func APIURL() string

APIURL is the control plane this conch signs in to: CONCH_CLOUD_URL, else config.toml's cloud api, else production. A signed-in device keeps using the server it signed in to (cloud.json), whatever this says later.

func AccountPath

func AccountPath() string

AccountPath is cloud.json.

func Bridge

func Bridge(ctx context.Context, s *relay.Session, in io.Reader, out io.Writer) error

Bridge carries conch's protocol between in/out and the machine's server: a line of in is a message to it, and each message back a line of out — what `conch bridge` does over ssh. It returns nil when in ends, and an error when the machine's end does first.

func Exec

func Exec(ctx context.Context, s *relay.Session, o ExecOptions) (int, error)

Exec runs a script on the machine as its user's login shell would — what `ssh host sh -c …` is elsewhere — and returns its exit status.

func Forget

func Forget() error

Forget drops this conch's sign-in without telling the server.

func ForgetKey

func ForgetKey(id string) error

ForgetKey drops the key pinned for machine id, so the next connection pins whatever it is given.

func IsMachineID

func IsMachineID(id string) bool

IsMachineID says whether id has the shape of a machine id.

func KeysPath

func KeysPath() string

KeysPath is where pinned keys are kept.

func SignedIn

func SignedIn() bool

SignedIn says whether this conch has a Conch Cloud account, from the file alone.

Types

type Account

type Account struct {
	API      string `json:"api"`
	DeviceID string `json:"device_id"`
	Handle   string `json:"handle,omitempty"`
	// Store says where the tokens are: "keychain", or "file" (here).
	Store         string    `json:"store"`
	AccessToken   string    `json:"access_token,omitempty"`
	RefreshToken  string    `json:"refresh_token,omitempty"`
	AccessExpires time.Time `json:"access_expires,omitzero"`
}

Account is what cloud.json holds.

func LoadAccount

func LoadAccount() (*Account, error)

LoadAccount reads cloud.json: ErrNotSignedIn without one.

type Activity

type Activity struct {
	Agents          []AgentActivity `json:"agents"`
	ClientsAttached int             `json:"clients_attached"`
	ProcessesBusy   bool            `json:"processes_busy,omitempty"`
	ReportedAt      time.Time       `json:"reported_at"`
}

Activity is the VM's last activity report (1.1.0).

type AgentActivity

type AgentActivity struct {
	Agent   string `json:"agent"`
	State   string `json:"state"`
	Project string `json:"project,omitempty"`
}

AgentActivity is one agent in a machine's activity.

type Allowance

type Allowance struct {
	RunningSeconds     int       `json:"running_seconds"`
	RunningSecondsUsed int       `json:"running_seconds_used"`
	StorageGB          int       `json:"storage_gb"`
	StorageGBUsed      float64   `json:"storage_gb_used"`
	MaxMachines        int       `json:"max_machines"`
	PeriodEnd          time.Time `json:"period_end,omitzero"`
}

Allowance is this month's share of the plan.

type Client

type Client struct {
	API  string
	HTTP *http.Client
	// contains filtered or unexported fields
}

Client calls the control plane as a signed-in device.

func FinishLogin

func FinishLogin(ctx context.Context, api string, da DeviceAuth) (*Client, error)

FinishLogin polls until the person approves the code (every interval seconds, five more after each slow_down), then keeps the tokens and returns the signed-in client.

func Open

func Open() (*Client, error)

Open is the signed-in account's client, or ErrNotSignedIn. It reads only what is on disk (and the Keychain): no request is made.

func (*Client) Account

func (c *Client) Account() Account

Account is what cloud.json says about this sign-in.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, id string) (ConnectInfo, error)

Connect is what is needed to open a tunnel to a machine; it wakes an asleep one.

func (*Client) CreateMachine

func (c *Client) CreateMachine(ctx context.Context, spec MachineCreate, idempotencyKey string) (Machine, error)

CreateMachine makes a machine, which answers at once in `creating`. The idempotency key makes asking twice (a retry) make one machine.

func (*Client) DeleteMachine

func (c *Client) DeleteMachine(ctx context.Context, id string) error

DeleteMachine destroys a machine and its disk.

func (*Client) Devices

func (c *Client) Devices(ctx context.Context) ([]Device, error)

Devices lists the devices signed in to the account.

func (*Client) Dial

func (c *Client) Dial(ctx context.Context, id string, say func(string)) (*relay.Session, error)

Dial opens a tunnel to the machine id, waking it and waiting for it first when it is asleep. say, if set, is told what is being waited on.

func (*Client) Events

func (c *Client) Events(ctx context.Context, on func(Event)) error

Events follows GET /v1/events, calling on for each event until ctx ends. A dropped stream is opened again after a pause, resuming from the last event's id (Last-Event-ID), so a machine's state is not missed across a reconnect. It returns only for ctx, or for an error trying again cannot mend: the device signed out, or the contract refused.

func (*Client) Logout

func (c *Client) Logout(ctx context.Context) error

Logout revokes this device's sign-in and forgets it. The tokens are forgotten even when the server cannot be told — signing out of this conch must always work — and the error then says the device is still listed on the account.

func (*Client) Machine

func (c *Client) Machine(ctx context.Context, id string) (Machine, error)

Machine is one machine.

func (*Client) Machines

func (c *Client) Machines(ctx context.Context) ([]Machine, error)

Machines lists the account's machines.

func (*Client) Me

func (c *Client) Me(ctx context.Context) (Me, error)

Me is the signed-in account. Its handle is kept in cloud.json, for saying who is signed in without asking.

func (*Client) Providers

func (c *Client) Providers(ctx context.Context) ([]Provider, error)

Providers lists where the account can run machines.

func (*Client) Sizes

func (c *Client) Sizes(ctx context.Context) (Sizes, error)

Sizes lists the sizes and regions the account may create.

func (*Client) Sleep

func (c *Client) Sleep(ctx context.Context, id string, force bool) (Machine, error)

Sleep puts a machine to sleep; ErrAgentsWorking unless force.

func (*Client) UpdateMachine

func (c *Client) UpdateMachine(ctx context.Context, id string, u MachineUpdate) (Machine, error)

UpdateMachine renames or resizes a machine, or changes its sleep.

func (*Client) WaitRunning

func (c *Client) WaitRunning(ctx context.Context, id string, say func(string)) (Machine, error)

WaitRunning returns the machine once it is running, waking it if it sleeps: for a command that was asked to go there, as a move is.

func (*Client) Wake

func (c *Client) Wake(ctx context.Context, id string) (Machine, error)

Wake starts or wakes a machine.

type ConnectInfo

type ConnectInfo struct {
	RelayURL  string    `json:"relay_url"`
	Room      string    `json:"room"`
	Ticket    string    `json:"ticket"`
	ServerKey string    `json:"server_key"`
	ExpiresAt time.Time `json:"expires_at"`
	State     string    `json:"state"`
}

ConnectInfo is what a client needs to open a tunnel to a machine.

type Device

type Device struct {
	ID         string    `json:"id"`
	Name       string    `json:"name"`
	Client     string    `json:"client"`
	CreatedAt  time.Time `json:"created_at"`
	LastSeenAt time.Time `json:"last_seen_at"`
	Current    bool      `json:"current"`
}

Device is a device signed in to the account.

type DeviceAuth

type DeviceAuth struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
	ExpiresIn               int    `json:"expires_in"`
	Interval                int    `json:"interval"`
}

DeviceAuth is POST /v1/auth/device's answer.

func StartLogin

func StartLogin(ctx context.Context, api, client, deviceName, conchVersion string) (DeviceAuth, error)

StartLogin asks api for a device code to show the person.

type Event

type Event struct {
	ID        string         `json:"-"`
	Type      string         `json:"type"`
	At        time.Time      `json:"at"`
	MachineID string         `json:"machine_id,omitempty"`
	Data      map[string]any `json:"data,omitempty"`
}

Event is one of GET /v1/events's server-sent events.

type ExecOptions

type ExecOptions struct {
	Script string
	// TTY runs it on a terminal of its own, Cols×Rows, which Resize
	// changes.
	TTY        bool
	Cols, Rows int
	Resize     <-chan [2]int
	Stdin      io.Reader // nil: none
	Stdout     io.Writer
	Stderr     io.Writer
}

ExecOptions is one script for Exec.

type KeyChangedError

type KeyChangedError struct {
	Machine string // its name, or id
	ID      string
	Pinned  time.Time
}

KeyChangedError is a machine whose key is not the one pinned, while the machine was not recreated.

func (*KeyChangedError) Error

func (e *KeyChangedError) Error() string

type Keychain

type Keychain interface {
	Get(account string) (string, error)
	Set(account, secret string) error
	Delete(account string) error
}

Keychain keeps a secret per account name. Tests replace it (SetKeychain) so that none ever reaches the developer's own Keychain.

func SetKeychain

func SetKeychain(k Keychain) Keychain

SetKeychain replaces the Keychain (nil: tokens in the file), returning the one it replaced. For tests.

type Machine

type Machine struct {
	ID           string           `json:"id"`
	Name         string           `json:"name"`
	Size         string           `json:"size"`
	Region       string           `json:"region"`
	State        string           `json:"state"`
	StateDetail  string           `json:"state_detail,omitempty"`
	StateSince   time.Time        `json:"state_since,omitzero"`
	Sleep        SleepPolicy      `json:"sleep"`
	MemorySleep  bool             `json:"memory_sleep,omitempty"`
	ConchVersion string           `json:"conch_version,omitempty"`
	ServerKey    string           `json:"server_key,omitempty"`
	CreatedAt    time.Time        `json:"created_at"`
	Activity     *Activity        `json:"activity,omitempty"`
	Provider     *MachineProvider `json:"provider,omitempty"`
}

Machine is a cloud machine.

type MachineCreate

type MachineCreate struct {
	Name     string       `json:"name"`
	Size     string       `json:"size"`
	Region   string       `json:"region,omitempty"`
	Snapshot string       `json:"snapshot,omitempty"`
	Sleep    *SleepPolicy `json:"sleep,omitempty"`
	Provider string       `json:"provider,omitempty"`
}

MachineCreate is POST /v1/machines's body.

type MachineProvider

type MachineProvider struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Kind  string `json:"kind"`
	Owner string `json:"owner"`
}

MachineProvider is where a machine runs (1.2.0).

type MachineUpdate

type MachineUpdate struct {
	Name  string       `json:"name,omitempty"`
	Size  string       `json:"size,omitempty"`
	Sleep *SleepPolicy `json:"sleep,omitempty"`
}

MachineUpdate is PATCH /v1/machines/{id}'s body.

type Me

type Me struct {
	ID        string    `json:"id"`
	Handle    string    `json:"handle"`
	Email     string    `json:"email,omitempty"`
	Plan      string    `json:"plan"`
	Allowance Allowance `json:"allowance"`
}

Me is the signed-in account (GET /v1/me).

type Problem

type Problem struct {
	Status            int    `json:"status"`
	Type              string `json:"type"`
	Title             string `json:"title"`
	Detail            string `json:"detail,omitempty"`
	Code              string `json:"code"`
	ContractSupported string `json:"contract_supported,omitempty"`
	RetryAfter        int    `json:"retry_after,omitempty"`
}

Problem is an error the control plane answered (RFC 9457, openapi.yaml Problem). errors.Is matches it against the Err values below by its code.

func (*Problem) Error

func (p *Problem) Error() string

func (*Problem) Is

func (p *Problem) Is(target error) bool

Is matches the problem's code to one of the Err values.

type Provider

type Provider struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Kind        string   `json:"kind"`
	Owner       string   `json:"owner"`
	Status      string   `json:"status"`
	Regions     []string `json:"regions"`
	Sizes       []string `json:"sizes"`
	MemorySleep bool     `json:"memory_sleep"`
	Default     bool     `json:"default"`
	Machines    int      `json:"machines,omitempty"`
}

Provider is where machines can run (1.2.0).

type Region

type Region struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

Region is where a machine can be made.

type Size

type Size struct {
	ID       string   `json:"id"`
	Name     string   `json:"name"`
	VCPU     int      `json:"vcpu"`
	MemoryGB int      `json:"memory_gb"`
	DiskGB   int      `json:"disk_gb"`
	Plans    []string `json:"plans"`
}

Size is a machine size the account may create.

type Sizes

type Sizes struct {
	Sizes   []Size   `json:"sizes"`
	Regions []Region `json:"regions"`
}

Sizes is GET /v1/sizes.

type SleepPolicy

type SleepPolicy struct {
	IdleSeconds          int `json:"idle_seconds,omitempty"`
	UnattendedMaxSeconds int `json:"unattended_max_seconds,omitempty"`
	ArchiveAfterSeconds  int `json:"archive_after_seconds,omitempty"`
}

SleepPolicy is a machine's sleep settings.

Directories

Path Synopsis
Package cloudtest is a fake Conch Cloud control plane for conch's tests: the client side of the contract on httptest — the device flow, tokens that rotate (a reused refresh token revokes the device, as the real one does), machines, connect with single-use tickets — and a relay that checks those tickets in front of conch's own.
Package cloudtest is a fake Conch Cloud control plane for conch's tests: the client side of the contract on httptest — the device flow, tokens that rotate (a reused refresh token revokes the device, as the real one does), machines, connect with single-use tickets — and a relay that checks those tickets in front of conch's own.

Jump to

Keyboard shortcuts

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