core

package
v0.2.13 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 22 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 core holds the domain operations the CLI performs.

Nothing here knows about terminals, flags, colour or cobra. Functions take plain arguments and return plain data, which means they can be tested without a network and reused unchanged by anything that needs them later, including an MCP tool server.

The dependency direction is one way and enforced by review: core may import api and clierr; nothing in core may import cmd, output or help.

Index

Constants

View Source
const (
	DNSCNAMETarget = "domains-management.outplane.app"
	DNSATarget     = "162.55.159.8"
)

DNS targets a reader has to put in their zone.

Both are the platform's published addresses, and a domain command without them is a command that tells somebody to go and look elsewhere. A host with a subdomain gets a CNAME; an apex domain cannot have one, so it gets an A record.

View Source
const (
	MaxEnvVars     = 250
	MaxEnvKeyLen   = 500
	MaxEnvValueLen = 5000
)

Limits the server enforces. They are duplicated here so that a violation is reported before a request is sent, naming the key that broke the rule; the server's own message names none of them.

View Source
const (
	MaxIPProfileName        = 100
	MaxIPProfileDescription = 255
	MaxCIDRLength           = 45
)

Limits the server enforces, duplicated so that a violation names the field rather than arriving as one sentence about the whole request.

View Source
const (
	MinVolumeGB = 10
	MaxVolumeGB = 50
)

Volume size bounds, which the server enforces and this restates so that a wrong one is refused before a disk is created at the wrong size.

View Source
const AgentLoopbackTimeout = 90 * time.Second

AgentLoopbackTimeout is the same wait when a coding agent is driving.

Shorter, and not for the user's sake. The console mints the token when Approve is pressed and posts it afterwards, so an approval that lands after this process has gone creates a live credential nobody receives and nobody can revoke from here. Agent harnesses kill a command on their own schedule, commonly at two minutes, and a CLI that outlives its own listener cannot even report what happened. Ending first keeps the last word.

View Source
const ConnectURL = "https://github.com/apps/out-plane-connect-run/installations/select_target"

ConnectURL is where a person grants or widens access to their repositories.

Printed by `outplane repos` every time, not only when the list is empty. The common case is not "nothing is connected" but "the repository I wanted is not among these", and that is fixed at the same address.

View Source
const (
	// DefaultShellCommand is what the platform runs when nothing is asked for.
	//
	// The choice is the server's and this is only a copy of it, kept so that a
	// message written before the connection exists can still name what will
	// run. Nothing is sent when the command is empty, so if the two ever
	// disagree the server's answer is the one that happens.
	DefaultShellCommand = "sh"
)
View Source
const HangarMaxPorts = 3

HangarMaxPorts is how many ports a Hangar can have open at once.

View Source
const HangarOwnPort = 7070

HangarOwnPort is the port the Hangar itself uses. It is never one a dev server can be reached on.

View Source
const LoopbackTimeout = 3 * time.Minute

LoopbackTimeout is how long the browser has to answer.

Long enough to sign in to the console first, create the token and read what is being approved. Short enough that a forgotten terminal does not hold a port open all afternoon.

View Source
const MaxBuildFilter = 2000

MaxBuildFilter is the length of one filter list, matching the console.

View Source
const MaxDisplayName = 45

MaxDisplayName is the server's limit.

View Source
const SourceContainerRegistry = "container-registry"

SourceContainerRegistry is the decoded provider that deploys a ready-made image rather than building one.

Several commands branch on it: an image reference means something only for this source, a failed deployment of one has no build output to read, and its "repository" is an image name. It is a constant so that those three places cannot disagree about the spelling.

Variables

View Source
var (
	PostgresVersions = []string{"14", "15", "16", "17", "18"}
	DatabaseRegions  = []string{
		"aws-us-east-1", "aws-us-east-2", "aws-us-west-2",
		"aws-eu-central-1", "aws-eu-west-2",
		"aws-ap-southeast-1", "aws-ap-southeast-2", "aws-sa-east-1",
	}
)

PostgresVersions and DatabaseRegions are what the server accepts. They are restated so that a wrong one is refused with the alternatives in hand, and because a region cannot be changed after creation.

AllLevels is every level a caller may ask for, in severity order.

View Source
var BuildMethods = []string{"dockerfile", "buildpack"}

BuildMethods are how a repository becomes an image.

View Source
var DefaultHangarAgents = []string{"claude-code", "codex"}

DefaultHangarAgents are installed when none are named, the same preselection the console's form makes.

View Source
var HangarAgents = []string{"codex", "claude-code", "pi", "omp", "devin", "opencode", "cursor"}

HangarAgents is the catalog of coding agents a Hangar can install, by id.

The list is the server's and is duplicated here for the reason InstanceTypes is: a wrong id is refused with the alternatives in hand rather than after a round trip. An agent the catalog gained after this release is refused by it, and the message says where the list came from.

View Source
var HangarIdleTimeouts = []int{15, 30, 60, 120, 360, 720, 1440}

HangarIdleTimeouts are the idle timeouts a Hangar may have, in minutes, at creation and afterwards. Never is always allowed besides these.

View Source
var InstanceTypes = []string{"op-20", "op-22", "op-34", "op-46", "op-58", "op-70", "op-82", "op-94"}

InstanceTypes are the sizes an application can run at, smallest first.

The list is the server's and is duplicated here so that a wrong one is refused with the alternatives in hand rather than after a round trip. A size the server has learned since this release is refused by a CLI that has not, which is the cost of listing them; the message says where the list came from.

View Source
var Methods = []string{"GET", "POST", "PUT", "PATCH", "DELETE"}

Methods are what this command will send. Anything else is a typo: the API serves no other verb, and sending one produces a 405 that reads like a missing endpoint.

View Source
var ReadMethods = []string{"GET", "HEAD"}

ReadMethods change nothing on the server, which is what decides whether the invocation needs acknowledging.

View Source
var Schemes = []string{"http", "h2c", "tcp"}

Schemes are how a port is served.

Functions

func AssignEnvGroup

func AssignEnvGroup(ctx context.Context, c *api.Client, groupID, appID string) error

AssignEnvGroup attaches a group to an application.

func AssignIPProfile

func AssignIPProfile(ctx context.Context, c *api.Client, profileID, appID string) error

AssignIPProfile attaches a profile to an application.

func BuildFinished

func BuildFinished(phase string) bool

BuildFinished reports whether a build has stopped, from the phase reported beside its output.

The phase is the build machine's own, not the deployment's: a build can have finished while the deployment is still releasing. For reading build output that is exactly the right question, and it is why this command needs no application reference to know when to stop.

Like deployment states, only the finished phases are listed. Anything else, including a phase this release has not seen, counts as still running.

func BuildRequestQuery

func BuildRequestQuery(f RequestFilter) string

BuildRequestQuery assembles the selector and its filters.

The order is deliberate and is what keeps a busy team's query cheap: label matchers first, because they select streams without reading anything; then the text filter, which reads lines but does not parse them; then the parse, which only the app filter needs.

func BuildRuntimeQuery

func BuildRuntimeQuery(teamSlug string, f LogFilter) string

BuildRuntimeQuery assembles the selector and its line filters.

Filtering happens at the gateway rather than here. Pulling everything back and discarding most of it locally would work for a quiet application and fall over on a busy one, which is exactly when somebody is reading logs.

func Call

Call sends the request and returns what came back.

func CheckCIDR

func CheckCIDR(cidr string) error

CheckCIDR rejects an address the server would.

A bare address is the common mistake and it deserves its own sentence: the server's message names the format and not what was wrong with this one, and somebody who wrote 10.0.0.1 meant 10.0.0.1/32.

func CheckDatabaseName

func CheckDatabaseName(name string) error

CheckDatabaseName rejects a name the server would refuse.

func CheckDatabaseRegion

func CheckDatabaseRegion(region string) error

func CheckDatabaseVersion

func CheckDatabaseVersion(version string) error

CheckDatabaseVersion and CheckDatabaseRegion refuse what the provider will not accept, before a request that would fail after a provisioning attempt.

func CheckDisplayName

func CheckDisplayName(name string) error

CheckDisplayName mirrors the server's rule, which is stricter than it looks: letters, numbers, spaces and hyphens, and nothing else. An underscore or a dot is refused, which is worth saying before a round trip rather than after.

func CheckDomainPath

func CheckDomainPath(path string) error

CheckDomainPath rejects a path the server would, and the one that would break certificate renewal.

func CheckEnvGroupName

func CheckEnvGroupName(name string) error

CheckEnvGroupName rejects a name the server would refuse.

func CheckEnvKey

func CheckEnvKey(key string) error

CheckEnvKey rejects a key the server would refuse, or explains why.

func CheckEnvValue

func CheckEnvValue(key, value string) error

CheckEnvValue rejects a value the server would refuse.

The value itself never appears in the message. An error about a credential that prints the credential is a leak on the one path where somebody is already watching the screen.

func CheckHangarIdleTimeout added in v0.2.13

func CheckHangarIdleTimeout(minutes *int) error

CheckHangarIdleTimeout refuses an idle timeout the server would refuse. Nil, for never, is always allowed.

func CheckHangarPorts added in v0.2.12

func CheckHangarPorts(ports []NewPort) error

CheckHangarPorts reports the first thing the server would refuse in a set about to be sent: an application's rules, then a Hangar's own two.

It takes the whole set rather than the ports named, because the limit is on the whole set. A port carried over with a scheme this release does not know is refused too, rather than sent back as a guess.

func CheckHost

func CheckHost(host string) error

CheckHost rejects what the server or DNS would.

func CheckIPProfile

func CheckIPProfile(p IPProfile) error

CheckIPProfile rejects what the server would, naming the field.

func CheckMountPath

func CheckMountPath(path string) error

CheckMountPath rejects a path the server would refuse.

func CheckPort

func CheckPort(p NewPort) error

CheckPort rejects a port the server would, naming which rule it broke.

The same rules `app create` applies, because they are the same rules: a port added later is not different from a port declared at creation, and having two answers to "is 70000 a port" would be a bug waiting for somebody to find it.

func CheckRegistryCredential

func CheckRegistryCredential(cred NewRegistryCredential) error

CheckRegistryCredential rejects what the server would, before a password travels anywhere.

func CheckScale

func CheckScale(instances int, instanceType string) error

CheckScale rejects a request the server would refuse, naming the field.

func CheckVolumeName

func CheckVolumeName(name string) error

CheckVolumeName rejects a name the server would refuse.

func CheckVolumeSize

func CheckVolumeSize(sizeGB int) error

CheckVolumeSize rejects a size outside what the platform provisions.

func ConnectionURL

func ConnectionURL(ctx context.Context, c *api.Client, id, role, database string) (string, error)

ConnectionURL assembles the string a client connects with.

It carries the role's password, so it is a credential and every command that handles it treats it as one.

func CreateDBRole

func CreateDBRole(ctx context.Context, c *api.Client, id, role string) error

CreateDBRole adds a login to an instance.

func CreateDBSchema

func CreateDBSchema(ctx context.Context, c *api.Client, id, database, owner string) error

CreateDBSchema adds a database to an instance, owned by an existing role.

func CreateDeployment

func CreateDeployment(ctx context.Context, c *api.Client, appID, imageRef string) (int, error)

CreateDeployment starts a build and returns its id.

The id is all the server returns: the create endpoint's result is a bare integer. Everything a caller wants to show about the new deployment, its status and when it started, comes from GetDeployment. That is one extra request, and it is worth it: reporting a status the CLI assumed rather than read is how "queued" becomes a false "ready".

func Cursor

func Cursor[T cursored](items []T) string

Cursor is the position to resume a follow from, or empty when there is none.

It takes the last item rather than the newest timestamp because the entries are already ordered, and re-deriving the maximum here would be a second place that has to agree with queryRange about which end is newest.

func DatabaseContents

func DatabaseContents(ctx context.Context, c *api.Client, id string) ([]DBRole, []DBSchema, error)

DatabaseContents lists the roles and the databases inside an instance.

func DeleteApp

func DeleteApp(ctx context.Context, c *api.Client, appID string) error

DeleteApp removes an application.

The platform refuses while a custom domain, an attached volume or a deployment in flight still exists, and answers all three with the same shape of error. Naming which one is the caller's job; see the delete command.

func DeleteDBRole

func DeleteDBRole(ctx context.Context, c *api.Client, id, role string) error

DeleteDBRole removes a login.

func DeleteDBSchema

func DeleteDBSchema(ctx context.Context, c *api.Client, id, database string) error

DeleteDBSchema removes a database and everything in it.

func DeleteDatabase

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

DeleteDatabase destroys a database and everything in it.

func DeleteEnvGroup

func DeleteEnvGroup(ctx context.Context, c *api.Client, groupID string) error

DeleteEnvGroup removes a group.

The server refuses while any application still uses it, so this is the one deletion on the platform that has to be unassigned first.

func DeleteHangar added in v0.2.11

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

DeleteHangar removes a Hangar and its disk.

func DeleteIPProfile

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

DeleteIPProfile removes a profile. The server refuses while it is attached to anything, and that refusal is relayed rather than predicted.

func DeleteRegistryCredential

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

DeleteRegistryCredential removes one.

func DeleteVolume

func DeleteVolume(ctx context.Context, c *api.Client, volumeID string) error

DeleteVolume destroys a disk and everything on it.

func EntryValues

func EntryValues(entries []EnvVar) map[string]string

EntryValues turns a group's entries back into the map an update has to send.

func Finished

func Finished(status string) bool

Finished reports whether a deployment has reached a state it will not leave.

func IdleTimeoutChoices added in v0.2.11

func IdleTimeoutChoices() []string

IdleTimeoutChoices are the idle timeouts as a person writes them: 15m, 1h, 24h, never.

func IdleTimeoutLabel added in v0.2.13

func IdleTimeoutLabel(minutes *int) string

IdleTimeoutLabel writes an idle timeout the way --idle-timeout takes it: whole hours in hours, anything else in minutes, and nil as never.

func NormalizeDomainPath

func NormalizeDomainPath(path string) string

NormalizeDomainPath matches the server's rule: trailing slashes go, empty becomes the root.

func NormalizeHost

func NormalizeHost(host string) string

NormalizeHost strips what a zone file allows and a stored record should not keep.

A trailing dot marks the root of the DNS tree and means nothing different about the domain, but stored with one it is a different string from the same host without: two routes, two certificates, and a lookup that misses.

func ParseMethod

func ParseMethod(s string) (string, error)

ParseMethod normalises one method argument.

It is restricted to letters because the value reaches the gateway inside a regular expression, where a stray character is either a syntax error or, in the case of a dot, a filter that silently matches more than it was asked to.

func ParseStatus

func ParseStatus(s string) (string, error)

ParseStatus turns one status argument into a pattern.

Both forms exist because both questions are real: "did anything fail" is a class, "where is that 404 coming from" is a code. A class becomes a pattern rather than an enumeration, so 418 is matched by 4xx without anybody having listed it.

func Pause

func Pause(ctx context.Context, c *api.Client, appID string, paused bool) error

Pause stops an application, or starts it again.

The replica count is untouched. Pausing derives the workload's replicas from the flag rather than writing zero, which is why resuming returns to whatever scale was configured rather than to one.

func PortNumbers

func PortNumbers(ports []Endpoint) []string

PortNumbers lists what an application serves, for an error that can say so.

func QueryVolumeUsage added in v0.2.12

func QueryVolumeUsage(ctx context.Context, c *api.Client, base string) (map[string]VolumeUsage, error)

QueryVolumeUsage reports the last known fill of every volume in the team, by volume id.

A volume with no sample in the window is absent rather than zero. One that has never been mounted has not been measured, which is not the same as empty.

func ReadBody

func ReadBody(value string, read func(string) ([]byte, error), stdin func() ([]byte, error)) ([]byte, error)

ReadBody reads --data, which may be a literal, a file or standard input.

@- is standard input, which is how a body larger than a command line arrives and the only form an agent can use without writing a temporary file. A literal that starts with @ has to become a file path, because a JSON document never starts with one.

func RemoveDomain

func RemoveDomain(ctx context.Context, c *api.Client, domainID string) error

RemoveDomain deletes a route.

func RestartHangar added in v0.2.12

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

RestartHangar starts a Hangar again on a new machine with the same disk.

The server starts it from what is saved: its variables, its groups and its ports, so a change saved since it last started takes effect. What stops is everything that runs, the session and its agents included. A Hangar with nothing running is refused with a conflict, because there is nothing to restart.

func SaveBuildSettings

func SaveBuildSettings(ctx context.Context, c *api.Client, appID string, s BuildSettings) error

SaveBuildSettings writes the whole set.

Every field goes every time, because the endpoint writes what it is given and an omission is a change: no start command clears the start command, and no build method stores one that decodes to nothing.

func Scale

func Scale(ctx context.Context, c *api.Client, appID string, instances int, instanceType string) error

Scale sets the replica count and the instance size together.

Together is not a convenience: the endpoint replaces both, and its request has a default of one replica, so sending a size alone would quietly scale the application down to a single instance. Callers therefore have to supply the current value for whichever one they are not changing, which the application list already reports.

func SetDisplayName

func SetDisplayName(ctx context.Context, c *api.Client, appID, displayName string) error

SetDisplayName changes the label an application is shown under.

Only the label. The name in the address is fixed at creation and no endpoint changes it, which is what the commands have to say plainly: somebody renaming an application usually wants the URL to follow, and it does not.

func SetEnv

func SetEnv(ctx context.Context, c *api.Client, appID string, values map[string]string) error

SetEnv adds or replaces variables, leaving every other key alone.

The merge happens on the server, which is what keeps two callers setting two different keys from overwriting each other.

func SetHangarIdleTimeout added in v0.2.13

func SetHangarIdleTimeout(ctx context.Context, c *api.Client, id string, minutes *int) error

SetHangarIdleTimeout changes how long a Hangar may sit idle before it pauses. Nil is never, which the server reads from a null.

Only the setting is written. Nothing restarts, and the next idle check reads the new value.

func SetHangarPaused added in v0.2.13

func SetHangarPaused(ctx context.Context, c *api.Client, id string, paused bool) error

SetHangarPaused pauses a Hangar, or resumes it.

Pausing stops its machine and keeps its disk, its ports and its variables; resuming starts it on a new machine with that disk, from the variables, groups and ports saved by then. The server returns early when the state already matches, and refuses a Hangar that never started with a conflict, because there is no machine to stop or start.

func SetPorts

func SetPorts(ctx context.Context, c *api.Client, appID string, ports []NewPort) error

SetPorts replaces an application's ports with exactly this set.

The name says replacement because that is what the request does. Callers wanting to change one port pass MergePorts' result, not one port.

func Succeeded

func Succeeded(status string) bool

Succeeded reports whether a deployment finished well.

Separate from Finished because the two questions have different wrong answers: treating an unknown state as finished stops a wait early, and treating one as successful reports a deploy that may have failed.

func UnassignEnvGroup

func UnassignEnvGroup(ctx context.Context, c *api.Client, assignmentID string) error

UnassignEnvGroup removes one assignment, by the assignment's own id.

func UnassignIPProfile

func UnassignIPProfile(ctx context.Context, c *api.Client, assignmentID string) error

UnassignIPProfile removes an attachment by its own id, which is why the caller has to look it up first: the pair of profile and application does not identify one.

func UnsetEnv

func UnsetEnv(ctx context.Context, c *api.Client, appID string, id int) error

UnsetEnv removes one variable by its own id.

Types

type AmbiguousAppError

type AmbiguousAppError struct {
	Ref     string
	Matches []App
}

AmbiguousAppError means a display name is shared. It carries the matches so the caller can be told to use a name or an id instead.

func (*AmbiguousAppError) Error

func (e *AmbiguousAppError) Error() string

func (*AmbiguousAppError) Names

func (e *AmbiguousAppError) Names() []string

Names lists the unique names of the tied applications, which are what the caller should use instead.

type AmbiguousDatabaseError

type AmbiguousDatabaseError struct {
	Ref   string
	Count int
}

AmbiguousDatabaseError means two databases share a name.

func (*AmbiguousDatabaseError) Error

func (e *AmbiguousDatabaseError) Error() string

type AmbiguousDomainError

type AmbiguousDomainError struct {
	Host  string
	Paths []string
}

AmbiguousDomainError means the host carries several routes and the path says which one.

func (*AmbiguousDomainError) Error

func (e *AmbiguousDomainError) Error() string

type AmbiguousEnvGroupError

type AmbiguousEnvGroupError struct {
	Ref   string
	Count int
}

AmbiguousEnvGroupError means two groups share a name.

func (*AmbiguousEnvGroupError) Error

func (e *AmbiguousEnvGroupError) Error() string

type AmbiguousHangarError added in v0.2.11

type AmbiguousHangarError struct {
	Ref     string
	Matches []Hangar
}

AmbiguousHangarError means a display name is shared.

func (*AmbiguousHangarError) Error added in v0.2.11

func (e *AmbiguousHangarError) Error() string

func (*AmbiguousHangarError) Names added in v0.2.11

func (e *AmbiguousHangarError) Names() []string

Names lists the unique names of the tied Hangars, which are what the caller should use instead.

type AmbiguousVolumeError

type AmbiguousVolumeError struct {
	Ref   string
	Count int
}

AmbiguousVolumeError means two disks share a name and only an id can say which was meant.

func (*AmbiguousVolumeError) Error

func (e *AmbiguousVolumeError) Error() string

type App

type App struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`

	// Status is the app's effective state and is the field to branch on.
	//
	// Pausing outranks the deployment status here, which mirrors the console's
	// rule: a paused app goes on reporting whatever its last deployment ended
	// as, so a caller reading DeploymentStatus alone would call a stopped app
	// "ready" and act on it.
	Status string `json:"status"`

	// DeploymentStatus is the raw state of the last deployment, kept so that
	// pausing hides nothing. For a paused app this is what it will return to.
	DeploymentStatus string `json:"deploymentStatus"`
	Paused           bool   `json:"paused"`

	// Instances is the configured replica count, which does not change when an
	// app is paused. Whether it is currently running is what Status says.
	Instances int    `json:"instances"`
	Size      string `json:"size"`

	// LastDeployedAt is when the last deployment started, and is the field that
	// answers "when did anything last happen here".
	//
	// UpdatedAt is not that field, which is why both exist: it is the app
	// record's own modification time, so editing a variable moves it and
	// deploying does not. The console draws its "Last deploy" column from the
	// same value this reads.
	LastDeployedAt string `json:"lastDeployedAt"`
	UpdatedAt      string `json:"updatedAt"`

	// CPULimitMillicores and MemoryLimitMB are what one instance may use. They
	// come from the instance type and are per pod rather than per app, which is
	// what makes a usage percentage mean the same thing at any replica count.
	CPULimitMillicores int `json:"cpuLimitMillicores"`
	MemoryLimitMB      int `json:"memoryLimitMb"`

	// Source is where the app's image comes from: "github" or
	// "container-registry". It decides whether an explicit image reference
	// means anything, so `deploy --image` can refuse a Git-sourced app here
	// rather than after a round trip.
	Source string `json:"source"`
}

App is one application, as the CLI thinks about it.

This is not the API's DTO. It is the shape commands want, which lets the wire format change without every command changing with it. The API has no OpenAPI response schemas today, so these types are written by hand against observed responses; keeping them separate is what makes that survivable.

func FindApp

func FindApp(ctx context.Context, c *api.Client, ref string) (App, error)

FindApp resolves a reference typed by a person into exactly one application.

This is the reference implementation for every argument declared with Resolves. The API has no lookup-by-name endpoint anywhere: every path parameter is a GUID, so turning "checkout" into an id is entirely the client's job, and the only way to do it is to list and match.

Matching is exact and never fuzzy, in any of the three fields. Resolving "check" to "checkout" would work until the day somebody creates "checkers", and the command being resolved for might be `app delete`. A near miss is reported as a miss, with the available names listed so the correction is one read away rather than another command away.

func ListApps

func ListApps(ctx context.Context, c *api.Client, search string) ([]App, error)

ListApps returns every application in the current team.

The API returns the whole set in one response: there is no pagination, no filtering and no server-side search. Callers therefore always receive a complete list, and any narrowing happens here rather than being requested from the server.

type AppDetail

type AppDetail struct {
	App

	// Repository and ImageRef are the two forms a source takes, and exactly one
	// of them is ever set. The API keeps both in a single column, so an app
	// built from a container image reports "nginx:latest" as its repository;
	// splitting them here means a reader never has to know that, and matches
	// the branch/imageRef pair a deployment already reports.
	Repository string `json:"repository"`
	Branch     string `json:"branch"`
	ImageRef   string `json:"imageRef"`
	SourceURL  string `json:"sourceUrl"`

	// PublicSource says the repository needs no credential to read. It is
	// always true for a container-registry app, which has no repository.
	PublicSource bool `json:"publicSource"`

	BuildMethod  string `json:"buildMethod"`
	Directory    string `json:"directory"`
	StartCommand string `json:"startCommand"`

	// IncludePaths and IgnorePaths decide whether a push builds at all. They
	// are glob patterns, one per line, and empty means every push builds.
	IncludePaths string `json:"includePaths"`
	IgnorePaths  string `json:"ignorePaths"`

	// URL is where the app can be reached, which is what somebody means by "the
	// app's URL". Endpoints has the rest.
	URL       string     `json:"url"`
	Endpoints []Endpoint `json:"endpoints"`

	CommitMessage string `json:"commitMessage"`
	CreatedAt     string `json:"createdAt"`
}

AppDetail is one application, with what the list cannot afford to fetch.

The list endpoint returns every application in one response and so cannot carry per-application detail; this is a second request for one of them. The difference that matters is Endpoints, and through them the public address, which is the question `app list` deliberately leaves unanswered.

func GetApp

func GetApp(ctx context.Context, c *api.Client, appID string) (AppDetail, error)

GetApp fetches one application by id.

type AppNotFoundError

type AppNotFoundError struct {
	Ref       string
	Available []string
}

AppNotFoundError carries the names that do exist, because "no such app" on its own sends the reader off to run another command to find out what is there.

func (*AppNotFoundError) Error

func (e *AppNotFoundError) Error() string

type BuildChange

type BuildChange struct {
	BuildMethod  *string
	Directory    *string
	StartCommand *string
	IncludePaths *string
	IgnorePaths  *string
	Image        *string
}

BuildChange is a request to change some of the settings. A nil field is one the caller did not mention and that has to survive untouched.

type BuildLogReader

type BuildLogReader struct {
	DeploymentID int
	// contains filtered or unexported fields
}

BuildLogReader walks a build log from wherever it last stopped.

It exists so that the two commands which read build output, `deploy create --follow` and `deploy logs`, share one piece of offset arithmetic instead of each keeping its own copy. The offset is the whole state, and getting it wrong in one place and not the other would mean one command silently repeating or skipping output.

It holds no client and does no printing: the caller decides how often to ask and what to do with the text.

func (*BuildLogReader) Next

func (r *BuildLogReader) Next(ctx context.Context, c *api.Client) (text string, finished bool, err error)

Next returns whatever has been written since the last call, and whether the build has stopped producing more.

An empty string is the normal answer while a build is still starting up, and is not an error. The offset never leaves this type: that is the entire point of it existing, since a caller keeping its own copy is how two commands come to repeat or skip output.

type BuildSettings

type BuildSettings struct {
	// FromRegistry says the application runs an image somebody else built,
	// which changes what can be set at all.
	FromRegistry bool

	BuildMethod  string
	Directory    string
	StartCommand string
	IncludePaths string
	IgnorePaths  string

	// Image is the reference a registry application runs. It is the same field
	// the API calls SourceRepository, under the name a reader would use.
	Image string
}

BuildSettings is everything the build settings endpoint writes.

func GetBuildSettings

func GetBuildSettings(ctx context.Context, c *api.Client, appID string) (BuildSettings, error)

GetBuildSettings reads what an application is built with.

func (BuildSettings) Apply

Apply returns the settings a change would produce, leaving everything it did not mention alone.

Pure, so what is about to be sent can be shown by --dry-run and held to in a test. The rules it does not encode are the server's own asymmetries, which are checked by Check: this only decides values.

func (BuildSettings) Check

func (s BuildSettings) Check(c BuildChange) error

Check rejects settings the server would refuse or silently drop.

Silently drop is the reason for half of it. A registry application accepts no build method and no filters, and the server neither stores nor mentions them, so a caller who set one would be told nothing and believe something happened.

type CreatedApp

type CreatedApp struct {
	AppID        string `json:"appId"`
	DeploymentID int    `json:"firstAppDeploymentId"`
}

CreatedApp is what the server returns, which is two identifiers.

func CreateApp

func CreateApp(ctx context.Context, c *api.Client, teamID string, app NewApp) (CreatedApp, error)

CreateApp creates an application and starts its first deployment.

type DBRole

type DBRole struct {
	Name string `json:"name"`
}

DBRole is a login the database accepts. DBSchema is a database inside the instance, which PostgreSQL also calls a database; the CLI keeps the platform's word for the instance and the provider's word for what is in it.

type DBSchema

type DBSchema struct {
	Name  string `json:"name"`
	Owner string `json:"owner"`
}

type DNSRecord

type DNSRecord struct {
	Type  string `json:"type"`
	Name  string `json:"name"`
	Value string `json:"value"`
}

DNSRecord is what to create in a zone for a host.

func RecordFor

func RecordFor(host string) DNSRecord

RecordFor works out which record a host needs. Purely local: there is nothing to ask the server, and a reader setting up DNS wants the answer before they have created anything.

type Database

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

	// Status is the lifecycle state, and the only one worth waiting for is
	// active. Provisioning means the provider has not finished.
	Status  string `json:"status"`
	Version string `json:"version"`
	Region  string `json:"region"`

	// Size is the provider's own compute unit, such as "0.25-1". It is not one
	// of the platform's instance codes and there is nothing to compare it with,
	// so it is passed through rather than interpreted.
	Size string `json:"size"`

	CreatedAt string `json:"createdAt"`
}

Database is one managed PostgreSQL instance.

func CreateDatabase

func CreateDatabase(ctx context.Context, c *api.Client, teamID, name, version, region string) (Database, error)

CreateDatabase provisions a managed PostgreSQL instance.

func FindDatabase

func FindDatabase(ctx context.Context, c *api.Client, ref string) (Database, error)

FindDatabase resolves a reference into exactly one database.

func GetDatabase

func GetDatabase(ctx context.Context, c *api.Client, id string) (Database, error)

GetDatabase reads one database's current state.

The detail endpoint also returns the provider's own project object, which is deliberately not decoded: it is somebody else's shape, it changes without notice, and nothing in the CLI needs it.

func ListDatabases

func ListDatabases(ctx context.Context, c *api.Client) ([]Database, error)

ListDatabases returns the team's managed databases, sorted by name.

type DatabaseNotFoundError

type DatabaseNotFoundError struct {
	Ref       string
	Available []string
}

DatabaseNotFoundError carries what does exist.

func (*DatabaseNotFoundError) Error

func (e *DatabaseNotFoundError) Error() string

type Deployment

type Deployment struct {
	ID    int    `json:"deploymentId"`
	AppID string `json:"appId"`

	// App is the application's name. The API fills it in only on the team-wide
	// feed, where a row would otherwise be unattributable; when a caller asked
	// about one application it already knows the answer and passes it in.
	App string `json:"app"`

	// Status is the decoded AppDeploymentStatus. An unrecognised value arrives
	// here as "unknown:N" and is never interpreted as either success or
	// failure; see WaitUntilFinished.
	Status string `json:"status"`

	Branch        string `json:"branch"`
	ImageRef      string `json:"imageRef"`
	CommitMessage string `json:"commitMessage"`
	StartedAt     string `json:"startedAt"`
	Duration      string `json:"duration"`
}

Deployment is one build-and-release of an application.

func GetDeployment

func GetDeployment(ctx context.Context, c *api.Client, appID string, id int) (Deployment, error)

GetDeployment reads one deployment's current state.

func ListDeployments

func ListDeployments(ctx context.Context, c *api.Client, appID, appName string) ([]Deployment, error)

ListDeployments returns one application's deployment history, newest first.

The order is the CLI's. The server returns them oldest first, which is the wrong way round for a history: the row somebody wants is almost always the last one, and a list that puts it at the bottom makes every reader scroll.

func ListTeamDeployments

func ListTeamDeployments(ctx context.Context, c *api.Client, limit int) ([]Deployment, error)

ListTeamDeployments returns the most recent deployments across the team.

This endpoint is the only paginated one in the API, and it pages from one rather than from zero. A caller wanting "the last twenty" asks for the first page of twenty; there is no cursor and no total, so there is nothing to report about what lies beyond it.

type Domain

type Domain struct {
	ID   string `json:"id"`
	Host string `json:"host"`
	Path string `json:"path"`

	// App and PortID are empty while the route exists but points nowhere, which
	// is the state a domain is created in.
	App    string `json:"app"`
	AppID  string `json:"appId"`
	PortID string `json:"portId"`

	// SSL is always true: the platform issues a certificate for every custom
	// domain. It is reported because a reader asks, not because it varies.
	SSL bool `json:"ssl"`

	// URL is the address the route answers on, which is the host, the path and
	// the scheme put together rather than something the API stores.
	URL string `json:"url"`
}

Domain is one route: a host, a path, and where it goes.

func AddDomain

func AddDomain(ctx context.Context, c *api.Client, host, path, portID string) (Domain, error)

AddDomain registers a route, optionally pointing it at a port.

func FindDomain

func FindDomain(ctx context.Context, c *api.Client, host, path string) (Domain, error)

FindDomain resolves a host, and a path when the host has more than one route.

A host with one route needs no path, which is the common case. A host with several is ambiguous by design rather than by accident, so the caller is told which paths exist instead of one being chosen.

func ListDomains

func ListDomains(ctx context.Context, c *api.Client) ([]Domain, error)

ListDomains returns the team's routes, sorted by host and then by path with the root first, which is the order somebody reads them in.

func PointDomain

func PointDomain(ctx context.Context, c *api.Client, domainID, portID, path string) (Domain, error)

PointDomain sends a route to a port, or to nowhere when portID is empty.

The same endpoint does both, and the path has to be sent either way: it is a full replacement, so omitting the path would move the route to the root.

type DomainNotFoundError

type DomainNotFoundError struct {
	Host      string
	Path      string
	Available []string
}

DomainNotFoundError carries what does exist.

func (*DomainNotFoundError) Error

func (e *DomainNotFoundError) Error() string

type Endpoint

type Endpoint struct {
	// PortID identifies the port to the API, which is what attaching a custom
	// domain needs: a domain is bound to a port record rather than to a port
	// number on an application.
	PortID string `json:"portId"`

	Port   int    `json:"port"`
	Scheme string `json:"scheme"`
	Public bool   `json:"public"`

	// URL is the platform address for this port, present only while the port is
	// public. A private port with a custom domain is still reachable, at that
	// domain and nowhere else.
	URL string `json:"url"`

	// CustomDomains are full addresses rather than bare host names, because the
	// scheme and the path are both configurable per domain and a host name on
	// its own is not something a reader can open or curl.
	CustomDomains []string `json:"customDomains"`
}

Endpoint is one port an application serves.

func FindPort

func FindPort(ports []Endpoint, number int) (Endpoint, bool)

FindPort looks up one port by number.

func ListPorts

func ListPorts(ctx context.Context, c *api.Client, appID string) ([]Endpoint, error)

ListPorts returns the ports an application serves, lowest first.

It reads the application detail, which is the only endpoint that carries them. Ports come back with their custom domains attached, and that is worth keeping: a reader deciding whether to remove a port wants to see what is pointed at it.

type EnvGroup

type EnvGroup struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`

	// UseInBuild and UseInRuntime say where the variables are injected. A
	// runtime group reaches the running container; a build group reaches the
	// build that produces its image. They are independent, and a group that is
	// neither reaches nothing.
	UseInBuild   bool `json:"useInBuild"`
	UseInRuntime bool `json:"useInRuntime"`

	Variables   int `json:"variables"`
	Assignments int `json:"assignments"`

	// Entries are the variables themselves. Only the detail endpoint fills
	// them in, and commands decide whether to show the values.
	Entries []EnvVar `json:"entries"`

	// AssignedApps are the applications using the group, which only the detail
	// endpoint carries. They matter more here than a count would: nothing
	// deploys these applications automatically, so knowing which ones they are
	// is what turns "the change takes effect at the next deployment" into a
	// list of deployments somebody can actually run.
	AssignedApps []EnvGroupAssignment `json:"assignedApps"`
}

EnvGroup is a shared set of variables.

func FindEnvGroup

func FindEnvGroup(ctx context.Context, c *api.Client, ref string) (EnvGroup, error)

FindEnvGroup resolves a reference into exactly one group.

Exact matching on the id and then the name, the same rule applications and volumes use: a near miss is reported rather than guessed, because the command being resolved for might be a deletion.

func GetEnvGroup

func GetEnvGroup(ctx context.Context, c *api.Client, groupID string) (EnvGroup, error)

GetEnvGroup returns one group, with its variables.

func ListEnvGroups

func ListEnvGroups(ctx context.Context, c *api.Client) ([]EnvGroup, error)

ListEnvGroups returns the team's groups, sorted by name.

func SaveEnvGroup

func SaveEnvGroup(ctx context.Context, c *api.Client, groupID string, g EnvGroup, values map[string]string) (EnvGroup, error)

SaveEnvGroup creates a group, or replaces one whole.

The same request body serves both, which is the API's shape and not a convenience: an update replaces the name, the description, the scope flags and every variable together. A caller changing one variable therefore has to send the rest, and the command that does it reads them first.

type EnvGroupAssignment

type EnvGroupAssignment struct {
	// ID is the assignment's own identifier, which is what removing one needs.
	ID string `json:"id"`

	GroupID   string `json:"groupId"`
	GroupName string `json:"groupName"`
	AppID     string `json:"appId"`
	AppName   string `json:"appName"`
	Variables int    `json:"variables"`

	// Kind is app or hangar. A change to the group reaches an application at
	// its next deployment and a Hangar the next time it starts.
	Kind string `json:"kind"`
}

EnvGroupAssignment is one group attached to one application.

func AppEnvGroups

func AppEnvGroups(ctx context.Context, c *api.Client, appID string) ([]EnvGroupAssignment, error)

AppEnvGroups lists the groups assigned to an application.

It is also how an assignment id is found: the pair of group and application does not identify one, and removing an assignment needs the record itself.

type EnvGroupNotFoundError

type EnvGroupNotFoundError struct {
	Ref       string
	Available []string
}

EnvGroupNotFoundError carries what does exist.

func (*EnvGroupNotFoundError) Error

func (e *EnvGroupNotFoundError) Error() string

type EnvVar

type EnvVar struct {
	// ID is the variable's own identifier, which removal needs. It is an
	// integer rather than a GUID: this is the one table in the API that
	// numbers its rows.
	ID int `json:"id"`

	Key   string `json:"key"`
	Value string `json:"value"`
}

EnvVar is one variable set on an application.

func FindEnv

func FindEnv(vars []EnvVar, key string) (EnvVar, bool)

FindEnv looks up a variable by key.

Matching is case-insensitive because the server compares that way when it decides whether an assignment replaces an existing variable. Reading and writing have to agree about what counts as the same key, or `env set path=x` would replace PATH while `env get path` reported nothing.

func ListEnv

func ListEnv(ctx context.Context, c *api.Client, appID string) ([]EnvVar, error)

ListEnv returns every variable set on an application, sorted by key.

The order is the CLI's, not the server's, because the server returns insertion order and a list that reshuffles itself every time somebody adds a variable cannot be diffed between two runs.

type HTTPRequest

type HTTPRequest struct {
	At time.Time

	// App is which application served it, derived from the proxy's service
	// name. Empty when that name does not have the expected shape; Service
	// always carries the original.
	App string

	Method string
	Status int
	Path   string
	Host   string

	// LatencyMs is the whole request as the client experienced it. OriginMs is
	// the part the application itself took, so the difference is the proxy's
	// own overhead plus any retry.
	LatencyMs float64
	OriginMs  float64

	// OriginStatus is what the application answered, which is not always what
	// the client got: the proxy answers on its own when the app is unreachable.
	OriginStatus int

	Bytes    int64
	Protocol string
	Scheme   string

	// ClientIP is the caller as far as it can be known: the proxy's own view is
	// the last hop, so a forwarded address is preferred when one is present.
	ClientIP string
	Country  string

	Service string
	// contains filtered or unexported fields
}

HTTPRequest is one request the proxy handled.

func QueryRequests

func QueryRequests(ctx context.Context, c *api.Client, base, teamSlug, query string, w LogWindow) ([]HTTPRequest, error)

QueryRequests fetches the access log.

A record that does not parse is skipped rather than reported. The selector admits only access-log streams, so anything unparseable is a line the proxy wrote in a shape this release does not know; dropping one is better than failing the whole query, and better than emitting a row of zeroes that reads like a real request that took no time and returned no status.

type Hangar added in v0.2.11

type Hangar struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`

	// Status follows App.Status: pausing outranks the deployment state.
	Status string `json:"status"`
	Paused bool   `json:"paused"`

	// Agents are the coding agents installed in it, by catalog id. Empty for a
	// Hangar that is a terminal only.
	Agents []string `json:"agents"`

	Size   string `json:"size"`
	DiskGB int    `json:"diskGb"`

	// DiskID is the home disk's volume id, which its disk usage is keyed by.
	// Empty when the server names none.
	DiskID string `json:"diskId"`

	// CPULimitMillicores and MemoryLimitMB are what its size allows, as on an
	// application. Zero when the server does not say.
	CPULimitMillicores int `json:"cpuLimitMillicores"`
	MemoryLimitMB      int `json:"memoryLimitMb"`

	// IdleTimeoutMinutes is nil for never. A pointer, because zero minutes and
	// never are different answers.
	IdleTimeoutMinutes *int `json:"idleTimeoutMinutes"`

	// Ports are what its dev servers are reached on, lowest first. Never nil.
	Ports []HangarPort `json:"ports"`

	CreatedAt string `json:"createdAt"`
}

Hangar is one Hangar, as the CLI thinks about it. See App for why this is not the API's DTO.

func CreateHangar added in v0.2.11

func CreateHangar(ctx context.Context, c *api.Client, h NewHangar) (Hangar, error)

CreateHangar creates a Hangar and starts it.

A Hangar that is created but cannot start is still returned, with status failed: the record exists and holds its name, which is the server's rule for an application whose first deployment fails too.

func FindHangar added in v0.2.11

func FindHangar(ctx context.Context, c *api.Client, ref string) (Hangar, error)

FindHangar resolves a reference typed by a person into exactly one Hangar.

The rules are FindApp's, for the same reasons: the id first, then the name, then a display name only when exactly one Hangar carries it.

func ListHangars added in v0.2.11

func ListHangars(ctx context.Context, c *api.Client) ([]Hangar, error)

ListHangars returns every Hangar in the current team. Like the application list, it is the whole set in one response.

func (Hangar) Endpoints added in v0.2.12

func (h Hangar) Endpoints() []Endpoint

Endpoints is the Hangar's ports in the shape MergePorts and WithoutPorts read, so that a Hangar's set changes by exactly the rules an application's does.

type HangarNotFoundError added in v0.2.11

type HangarNotFoundError struct {
	Ref       string
	Available []string
}

HangarNotFoundError carries what does exist.

func (*HangarNotFoundError) Error added in v0.2.11

func (e *HangarNotFoundError) Error() string

type HangarPort added in v0.2.12

type HangarPort struct {
	Port   int    `json:"port"`
	Scheme string `json:"scheme"`
	Public bool   `json:"public"`

	// URL is the outside address, present only while the port is public: an
	// https address for http and h2c, a host and a port number for tcp.
	URL string `json:"url"`

	// Internal is {name}:{port}, where the team's applications reach it.
	Internal string `json:"internal"`
}

HangarPort is one port a Hangar has open for its dev servers.

It is an application's port with one address more. The team's applications reach a Hangar by its name, so every open port has an internal address, public or not, and a public one has an outside address besides.

func SetHangarPorts added in v0.2.12

func SetHangarPorts(ctx context.Context, c *api.Client, h Hangar, ports []NewPort) ([]HangarPort, error)

SetHangarPorts replaces a Hangar's ports with exactly this set and returns what was saved, with the addresses the server assigned.

type IPAssignment

type IPAssignment struct {
	// ID is the assignment's own identifier, which removing one needs.
	ID      string `json:"id"`
	AppID   string `json:"appId"`
	AppName string `json:"app"`
}

IPAssignment is one application a profile is attached to.

func FindAssignment

func FindAssignment(p IPProfile, appName, appID string) (IPAssignment, bool)

FindAssignment locates the attachment to one application, which unassigning needs and which the pair alone does not identify.

type IPProfile

type IPProfile struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`

	Rules       []IPRule `json:"rules"`
	Assignments int      `json:"assignments"`

	// AssignedApps are the applications using it, which only the detail
	// endpoint carries. They matter more than the count: attaching a profile
	// changes who can reach an application, so knowing which ones are affected
	// is the difference between a safe change and an outage.
	AssignedApps []IPAssignment `json:"assignedApps"`

	CreatedAt string `json:"createdAt"`
}

IPProfile is one profile.

func AppIPProfiles

func AppIPProfiles(ctx context.Context, c *api.Client, appID string) ([]IPProfile, error)

AppIPProfiles lists the profiles attached to an application.

func FindIPProfile

func FindIPProfile(ctx context.Context, c *api.Client, ref string) (IPProfile, error)

FindIPProfile resolves a reference into exactly one profile, matching the id and then the name, as every other resource does.

func GetIPProfile

func GetIPProfile(ctx context.Context, c *api.Client, id string) (IPProfile, error)

GetIPProfile reads one in full, which is the only way to see its rules and the applications it is attached to.

func ListIPProfiles

func ListIPProfiles(ctx context.Context, c *api.Client) ([]IPProfile, error)

ListIPProfiles returns the team's profiles, sorted by name.

func SaveIPProfile

func SaveIPProfile(ctx context.Context, c *api.Client, id string, p IPProfile) (IPProfile, error)

SaveIPProfile creates a profile, or replaces one whole.

The same body serves both, which is the API's shape: an update replaces the name, the description and every rule together, so a caller changing one rule has to send the rest and the command that does it reads them first.

type IPProfileNotFoundError

type IPProfileNotFoundError struct {
	Ref       string
	Available []string
}

IPProfileNotFoundError carries what does exist.

func (*IPProfileNotFoundError) Error

func (e *IPProfileNotFoundError) Error() string

type IPRule

type IPRule struct {
	CIDR        string `json:"cidr"`
	Description string `json:"description"`
}

IPRule is one network the profile lets through.

type Instance

type Instance struct {
	Name string `json:"name"`

	// Phase is the runtime's own word for what the instance is doing:
	// Pending, Running, Succeeded, Failed or Unknown. It is passed through
	// rather than translated, because it is a term a reader will find in every
	// other tool they use.
	Phase string `json:"phase"`

	// Ready is whether it is accepting traffic. An instance can be Running and
	// not ready, which is exactly the state worth seeing during a rollout.
	Ready bool `json:"ready"`

	// State is the platform's own reading of the lifecycle, and the field to
	// branch on. Phase is the runtime's raw word; this is what the platform
	// makes of it, and it distinguishes "starting" from "failing", which phase
	// alone cannot.
	State string `json:"state"`

	// RestartCount is how many times the container has restarted since the
	// instance was created. It is the only field that shows a crash loop which
	// has since recovered: everything else about that instance reads healthy.
	RestartCount int `json:"restartCount"`

	// Reason says why it is not up, in one sentence. Empty while it is running
	// normally or simply still starting.
	Reason string `json:"reason"`

	Container string `json:"container"`

	// CreatedAt is when the instance came into being, and StartedAt is when the
	// container running now started. They are seconds apart on a healthy
	// instance and hours apart on one that has restarted, which is the whole
	// reason both are reported: "up for" measures from the second.
	CreatedAt string `json:"createdAt"`
	StartedAt string `json:"startedAt"`

	// LastExitCode is what the previous container exited with, when there was
	// one. It is the application's own code, so 137 means it was killed for
	// using more memory than it was allowed.
	LastExitCode *int `json:"lastExitCode"`

	// DeploymentID ties an instance back to the row in `deploy list` that put
	// it there. Zero on an instance older than the platform variables.
	DeploymentID int `json:"deploymentId"`
}

Instance is one running copy of an application.

func AppInstances

func AppInstances(ctx context.Context, c *api.Client, appID string) ([]Instance, error)

AppInstances lists what is currently running.

This is the live answer, from the cluster rather than from the database, so it disagrees with the configured replica count exactly when something is wrong: during a rollout, while an instance is restarting, or when one cannot be scheduled.

type LogChunk

type LogChunk struct {
	Text string

	// Offset is the byte position to send with the next request. Build logs
	// are polled by offset rather than streamed, so this is what makes the
	// next call return only what is new.
	Offset int64

	// ProcessStatus is the build process's own state, reported alongside the
	// text. It is not the deployment status and is not decoded here.
	ProcessStatus string
}

LogChunk is one slice of a build log, plus where to resume from.

func BuildLogs

func BuildLogs(ctx context.Context, c *api.Client, id int, offset int64) (LogChunk, error)

BuildLogs fetches the part of a build log after offset.

Pass the Offset from the previous chunk to get only what is new; pass zero to start from the beginning.

type LogFilter

type LogFilter struct {
	// Apps limits the query to these applications. Empty means the whole team.
	Apps []string

	// Search is a case-insensitive substring the line must contain.
	Search string

	// Levels keeps only lines that look like one of these. Empty means all.
	Levels []LogLevel
}

LogFilter narrows a runtime log query.

type LogLevel

type LogLevel string

LogLevel narrows a query to lines that look like a given severity.

const (
	LevelError   LogLevel = "error"
	LevelWarning LogLevel = "warning"
	LevelInfo    LogLevel = "info"
	LevelDebug   LogLevel = "debug"
	LevelTrace   LogLevel = "trace"
)

func ParseLevel

func ParseLevel(s string) (LogLevel, error)

ParseLevel accepts a level name, or reports the ones that exist.

type LogLine

type LogLine struct {
	// At is when the line was written, as reported by the collector.
	At time.Time

	// Text is the line itself, with no timestamp prefix: the gateway keeps the
	// two apart and re-joining them would stop `outplane logs | grep` matching
	// what the reader sees.
	Text string

	// App is which application produced it, which matters when the query
	// covers a whole team.
	App string
	// contains filtered or unexported fields
}

LogLine is one line an application wrote.

func QueryLogs

func QueryLogs(ctx context.Context, c *api.Client, base, teamSlug, query string, w LogWindow) ([]LogLine, error)

QueryLogs fetches an application's output.

type LogWindow

type LogWindow struct {
	Since time.Duration
	Limit int
	// contains filtered or unexported fields
}

LogWindow is the span and size of one query.

func (LogWindow) After

func (w LogWindow) After(cursor string) LogWindow

After returns a window that asks only for lines newer than cursor.

type Loopback

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

Loopback is a listener waiting for one token.

func Listen

func Listen(origin string) (*Loopback, error)

Listen opens a loopback port and starts waiting.

The port is chosen by the operating system. A fixed one would collide with a second CLI signing in at the same time, and worse, would be a port anything on the machine could squat on before this process asked for it. Listen opens the port, allowing deliveries from one origin.

origin is the console this CLI is configured against. It is the only page allowed to answer, which matters more here than it looks: a browser will let any page it has open reach a loopback port, so the origin check is what keeps the listener talking to the console alone.

func (*Loopback) CallbackURL

func (l *Loopback) CallbackURL() string

CallbackURL is where the console posts the token.

func (*Loopback) Close

func (l *Loopback) Close() error

Close stops listening. Safe to call more than once.

func (*Loopback) State

func (l *Loopback) State() string

State is the value the console has to send back.

func (*Loopback) Wait

func (l *Loopback) Wait(ctx context.Context) (string, error)

Wait blocks until the browser delivers a token, the caller interrupts, or the wait runs out.

A timeout is not a failure of the flow; it usually means the browser opened somewhere the user did not see. The caller falls back to asking for a paste, so this reports plainly rather than dramatically.

func (*Loopback) WaitFor added in v0.2.9

func (l *Loopback) WaitFor(ctx context.Context, timeout time.Duration) (string, error)

WaitFor is Wait with the deadline named by the caller.

type Mount

type Mount struct {
	VolumeID string
	Path     string
}

Mount is an existing volume and where it should appear in the container.

type NewApp

type NewApp struct {
	Name string

	// Repository and Image are the two sources, and exactly one is given.
	// Repository is "owner/name" and needs a branch; Image is a container
	// reference and forbids one, because there is nothing to build.
	Repository string
	Branch     string
	PublicRepo bool
	Image      string

	BuildMethod  string
	Directory    string
	StartCommand string

	Instances    int
	InstanceType string

	Ports []NewPort
	Env   map[string]string

	// Volumes and EnvGroups reference things that already exist, by id.
	// Attaching is best effort on the server: one it cannot attach is skipped
	// and the creation succeeds regardless.
	Volumes   []Mount
	EnvGroups []string
}

NewApp is everything needed to create an application.

func (NewApp) Check

func (a NewApp) Check() error

Check reports the first thing the server would refuse.

One at a time rather than all at once, because the server reports one too and a caller fixing them one by one gets the same experience either way.

type NewHangar added in v0.2.11

type NewHangar struct {
	Name string

	// Agents are catalog ids. Empty means a terminal only.
	Agents []string

	Env map[string]string

	// EnvGroupIDs are ids, already resolved, in the order they were given. The
	// order matters: when two groups set the same key, it decides which wins.
	EnvGroupIDs []string

	// IdleTimeoutMinutes is nil for never.
	IdleTimeoutMinutes *int
}

NewHangar is everything needed to create a Hangar.

func (NewHangar) Check added in v0.2.11

func (h NewHangar) Check() error

Check reports the first thing the server would refuse, one at a time as NewApp.Check does.

type NewPort

type NewPort struct {
	Port   int
	Scheme string
	Public bool
}

NewPort is one port the application will serve.

func MergePorts

func MergePorts(existing []Endpoint, incoming []NewPort) []NewPort

MergePorts is the full set to send when some ports are being changed.

A port already there is replaced by the incoming one; a port that is not mentioned is carried through untouched. That carrying is the whole point: without it, adding a port would delete every other one.

func WithoutPorts

func WithoutPorts(existing []Endpoint, numbers []int) []NewPort

WithoutPorts is the full set to send when some ports are being removed.

Every other port is carried through, for the same reason MergePorts carries them: the request that removes one port is the same request that would remove all of them.

type NewRegistryCredential

type NewRegistryCredential struct {
	Name     string
	Server   string
	Username string
	Password string
}

NewRegistryCredential is what creating one needs.

type RawRequest

type RawRequest struct {
	Method string
	Path   string
	Body   []byte
}

RawRequest is one arbitrary call, already checked.

func NewRawRequest

func NewRawRequest(method, path string, query []string, body []byte) (RawRequest, error)

NewRawRequest turns what somebody typed into a request, or explains why it is not one.

Query parameters arrive separately from the path because a shell eats an ampersand: `--query a=1 --query b=2` needs no quoting, and a path that already carries a query string still works. The two are merged rather than one winning, so neither form is a trap.

func (RawRequest) Reads

func (r RawRequest) Reads() bool

Reads reports a request that cannot change anything.

type RegistryCredential

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

	// Server is the registry's host, as the runtime needs it: ghcr.io,
	// registry.gitlab.com, an account-specific ECR host.
	Server string `json:"server"`

	Username  string `json:"username"`
	CreatedAt string `json:"createdAt"`
}

RegistryCredential is one stored login.

func CreateRegistryCredential

func CreateRegistryCredential(ctx context.Context, c *api.Client, cred NewRegistryCredential) (RegistryCredential, error)

CreateRegistryCredential stores a login.

func FindRegistryCredential

func FindRegistryCredential(ctx context.Context, c *api.Client, ref string) (RegistryCredential, error)

FindRegistryCredential resolves a reference into exactly one credential, matching the id first and then the name, as every other resource does.

func ListRegistryCredentials

func ListRegistryCredentials(ctx context.Context, c *api.Client) ([]RegistryCredential, error)

ListRegistryCredentials returns the team's credentials, sorted by name.

type RegistryCredentialNotFoundError

type RegistryCredentialNotFoundError struct {
	Ref       string
	Available []string
}

RegistryCredentialNotFoundError carries what does exist.

func (*RegistryCredentialNotFoundError) Error

type Repo

type Repo struct {
	FullName string `json:"fullName"`
	Name     string `json:"name"`
	Private  bool   `json:"private"`
	Language string `json:"language"`
	Branch   string `json:"defaultBranch"`
	Archived bool   `json:"archived"`
	URL      string `json:"url"`

	// Provider names where the repository lives. Only one exists today, and it
	// is reported anyway so that a caller written now keeps working when a
	// second one appears rather than having to learn a new field.
	Provider string `json:"provider"`
}

Repo is a repository the signed-in user can deploy from.

func ListRepos

func ListRepos(ctx context.Context, c *api.Client) ([]Repo, error)

ListRepos returns every repository the token's user can deploy from.

Every one: the endpoint accepts page and per-page arguments and applies them to each connected installation separately, then concatenates the results, so asking for "page 2" returns an arbitrary slice of each rather than the second page of anything. The CLI does not offer pagination it cannot honour, and says so in the command's automation notes.

This is the one call in the CLI that depends on the token knowing which user created it. A token without that claim reaches the server as nobody and is told it has no installations.

type RequestFilter

type RequestFilter struct {
	// App is one application's name. It is matched against the proxy's service
	// name rather than a label, because there is no label for it.
	App string

	// Methods are upper-case verbs. Empty means all of them.
	Methods []string

	// Statuses are already-expanded patterns from ParseStatus: "404" matches
	// one code, "5.." matches a class.
	Statuses []string

	// Search is case-insensitive text the raw record must contain. It is
	// applied before parsing, so it reaches every field at once, including
	// ones this type does not model.
	Search string
}

RequestFilter narrows an access-log query. Every field is optional, and an empty filter means every request the team received.

type Shell

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

Shell is a live terminal session, on an instance or in a Hangar.

func ConnectHangar added in v0.2.11

func ConnectHangar(ctx context.Context, c *api.Client, id string) (*Shell, error)

ConnectHangar joins the session a Hangar keeps running.

Nothing is asked for beyond which Hangar. The server decides what the session is, and a Hangar that is not running is refused with a conflict before anything opens.

func OpenShell

func OpenShell(ctx context.Context, c *api.Client, appID, instance, command string) (*Shell, error)

OpenShell starts a session on one instance of an application.

instance is a name from AppInstances. The server checks that it belongs to this application before it execs into anything, so an instance borrowed from somewhere else is refused there rather than trusted here.

command is what to run, empty meaning the platform's default shell. An image that ships no shell fails the exec, and the server explains that in the session's own output rather than in an error: by then the socket is open and there is nowhere else to say it.

func (*Shell) Close

func (s *Shell) Close() error

Close ends the session, so the far end sees somebody leaving rather than a connection that died.

func (*Shell) Keepalive

func (s *Shell) Keepalive(ctx context.Context)

Keepalive holds an idle session open until the context ends.

A ping that goes unanswered ends the session with an error, which is the point: the alternative is a terminal that keeps accepting input nobody is receiving. Failure needs no report here, because the read loop is about to make the same discovery and it is the one talking to the reader.

func (*Shell) Resize

func (s *Shell) Resize(ctx context.Context, cols, rows int) error

Resize tells the far end how large the terminal is now.

A session starts at whatever size the runtime picked, which is not the reader's, so this is sent once on connecting and again whenever the window changes. A non-positive size is dropped rather than sent: the server would substitute 80x24 for it, and a window that briefly reports zero rows during a resize would leave the far end wrapping at a width nobody has.

func (*Shell) Send

func (s *Shell) Send(ctx context.Context, keys []byte) error

Send forwards keystrokes to the far end.

The frame carries them as a JSON string, so what arrives has to be valid UTF-8. A read from a terminal can end in the middle of a character: paste a paragraph of anything but ASCII and eventually one will straddle the buffer boundary. The trailing piece is held back and sent with the bytes that complete it, because encoding it as it stands would turn it into a replacement character and the far end would receive something nobody typed.

Send keeps that leftover, so it is the one method here that is not safe to call concurrently. Nothing needs to: keystrokes come from the one goroutine reading the terminal.

func (*Shell) Stream

func (s *Shell) Stream(ctx context.Context, w io.Writer) error

Stream copies everything the far end writes to w, until the session ends.

What arrives is already formatted for a terminal: escape sequences, carriage returns, colour, cursor movement. It goes through untouched and unbuffered, because anything else would be a second terminal emulator with its own bugs, and the reader already has a working one.

type Usage

type Usage struct {
	App string `json:"app"`

	CPUMillicores int   `json:"cpuMillicores"`
	MemoryBytes   int64 `json:"memoryBytes"`

	// Percent is nil when the limit is unknown rather than 0, because 0% and
	// "not known" lead to opposite decisions about whether to scale.
	CPUPercent    *int `json:"cpuPercent"`
	MemoryPercent *int `json:"memoryPercent"`

	NetworkInBps  float64 `json:"networkInBps"`
	NetworkOutBps float64 `json:"networkOutBps"`
	DiskReadBps   float64 `json:"diskReadBps"`
	DiskWriteBps  float64 `json:"diskWriteBps"`

	// Instances is how many pods are reporting, which is what is actually
	// running. It differs from the configured replica count while an app is
	// starting, stopping or partly crashed, and that difference is the point.
	Instances int `json:"instances"`

	CPULimitMillicores int `json:"cpuLimitMillicores"`
	MemoryLimitMB      int `json:"memoryLimitMb"`
}

Usage is one application's current resource use.

Every rate is an average over the last two minutes, because that is what a rate is: there is no instantaneous CPU usage to report. A number here is therefore slightly behind a spike and will not show one that lasted seconds.

func QueryUsage

func QueryUsage(ctx context.Context, c *api.Client, base string, apps []App) ([]Usage, error)

QueryUsage reports current usage for the given applications.

Rows come from the application list rather than from the metrics, and the order is the caller's. An app with no pods therefore appears with zeroes, which is the honest answer for something paused or crash-looping, and a pod belonging to no application is ignored: a build runs in the same place and is not an application's usage.

type Volume

type Volume struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	SizeGB int    `json:"sizeGb"`

	// Status is "attached" or "detached", and App and MountPath are set only
	// for the first. They are reported separately rather than derived from one
	// another so that a caller can branch on the state without parsing a name.
	Status    string `json:"status"`
	App       string `json:"app"`
	AppID     string `json:"appId"`
	MountPath string `json:"mountPath"`

	// AccessMode is how many instances may mount it at once. Every volume the
	// platform creates is ReadWriteOnce, so this is reported and never chosen.
	AccessMode string `json:"accessMode"`
	CreatedAt  string `json:"createdAt"`
}

Volume is a persistent disk.

func AppVolumes

func AppVolumes(ctx context.Context, c *api.Client, appID string) ([]Volume, error)

AppVolumes returns the volumes attached to one application.

func AttachVolume

func AttachVolume(ctx context.Context, c *api.Client, volumeID, appID, mountPath string) (Volume, error)

AttachVolume mounts a disk on an application.

func CreateVolume

func CreateVolume(ctx context.Context, c *api.Client, name string, sizeGB int, appID, mountPath string) (Volume, error)

CreateVolume makes a disk, optionally attaching it in the same call.

The server creates it detached and then attaches, so a failure to attach leaves a disk that exists and is not mounted. That is worth knowing before retrying: the retry would create a second one.

func DetachVolume

func DetachVolume(ctx context.Context, c *api.Client, volumeID string) (Volume, error)

DetachVolume unmounts a disk, keeping the disk and its contents.

func FindVolume

func FindVolume(ctx context.Context, c *api.Client, ref string) (Volume, error)

FindVolume resolves a reference into exactly one volume.

The same exact-match rule as applications, for the same reason: resolving a near miss would work until two disks share a prefix, and the command being resolved for might be a deletion. Names are unique in practice but not enforced, so a tie is reported rather than guessed.

func ListVolumes

func ListVolumes(ctx context.Context, c *api.Client) ([]Volume, error)

ListVolumes returns every volume in the team, sorted by name.

type VolumeNotFoundError

type VolumeNotFoundError struct {
	Ref       string
	Available []string
}

VolumeNotFoundError carries what does exist, so the correction is one read away rather than another command away.

func (*VolumeNotFoundError) Error

func (e *VolumeNotFoundError) Error() string

type VolumeUsage added in v0.2.12

type VolumeUsage struct {
	UsedBytes     int64
	CapacityBytes int64

	// Percent is nil when the capacity is not known, as for Usage.
	Percent *int
}

VolumeUsage is one volume's last known fill.

Jump to

Keyboard shortcuts

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