Documentation
¶
Overview ¶
Package sprites is the Fly Sprites client (sprites-provider.md): the REST calls a fresh-Sprite-per-job provider needs, the WebSocket exec channel, the error classes of 1.2 and the pre-attach / attached classification of 1.3. The provider (S.2) wires it into Launch.
Facts the design could not verify (its section 9) are assumed in the worst direction and marked "assumed" below; the live probes settle them.
Index ¶
- Constants
- Variables
- func AgentCmd(sha string, sudo bool, args ...string) ([]string, error)
- func EncodeName(secret []byte, prefix, install, size, job8 string, expiry time.Time) string
- func PreAttach(id string, err error) error
- func ReadFrames(r io.Reader, fn func(agent.Frame) error) error
- func TokenOrg(tok string) (slug string, ok bool)
- func VerifyName(secret []byte, name string) bool
- type AttachOptions
- type Checkpoint
- type Cleaner
- type Client
- func (c *Client) ApplyBuildPolicies(ctx context.Context, name string, build NetworkPolicy, res Resources) error
- func (c *Client) ApplyJobPolicy(ctx context.Context, name string, job NetworkPolicy) error
- func (c *Client) Attach(ctx context.Context, name string, o AttachOptions) (*Session, error)
- func (c *Client) CreateCheckpoint(ctx context.Context, name, comment string) (Checkpoint, error)
- func (c *Client) CreateSprite(ctx context.Context, name string, labels map[string]string) (Sprite, error)
- func (c *Client) DeleteCheckpoint(ctx context.Context, name, id string) error
- func (c *Client) DeleteSprite(ctx context.Context, name string) error
- func (c *Client) Endpoint() string
- func (c *Client) Exec(ctx context.Context, name string, r ExecRequest) (*Session, error)
- func (c *Client) FSRead(ctx context.Context, name, path string, w io.Writer) (int64, error)
- func (c *Client) FSWrite(ctx context.Context, name, path string, data []byte) error
- func (c *Client) GetCheckpoint(ctx context.Context, name, id string) (Checkpoint, error)
- func (c *Client) GetSprite(ctx context.Context, name string) (Sprite, error)
- func (c *Client) GoString() string
- func (c *Client) ListCheckpoints(ctx context.Context, name string) ([]Checkpoint, error)
- func (c *Client) ListConnections(ctx context.Context) ([]string, error)
- func (c *Client) ListSprites(ctx context.Context, prefix string) ([]Sprite, error)
- func (c *Client) Org() string
- func (c *Client) Organization(ctx context.Context) (OrgInfo, error)
- func (c *Client) Raw(ctx context.Context, method, path string, q url.Values, body any) (int, []byte)
- func (c *Client) Read(ctx context.Context, name, agentSHA, job, file string, off int64, w io.Writer) (int, error)
- func (c *Client) RestoreCheckpoint(ctx context.Context, name, id string) error
- func (c *Client) Run(ctx context.Context, name string, r ExecRequest, stdin []byte) (ExecResult, error)
- func (c *Client) Secrets() []string
- func (c *Client) String() string
- func (c *Client) Sudo() bool
- func (c *Client) Tail(ctx context.Context, name, agentSHA, job string, offs map[string]int64, ...) error
- type ExecRequest
- type ExecResult
- type NetRule
- type NetworkPolicy
- type NotFoundError
- type Options
- type OrgInfo
- type OrgMismatchError
- type OrgTokenError
- type Parsed
- type PolicyMismatchError
- type Provider
- func (p *Provider) DoctorLines(ctx context.Context) []provider.DoctorLine
- func (p *Provider) Estimate(_ context.Context, j *provider.JobSpec) (config.Micros, error)
- func (p *Provider) Fetch(ctx context.Context, h provider.Handle, a provider.ArtifactSpec, w io.Writer) error
- func (p *Provider) Info() provider.Info
- func (p *Provider) Launch(ctx context.Context, j *provider.JobSpec) (provider.Handle, error)
- func (p *Provider) List(ctx context.Context, prefixes []string) ([]provider.Resource, error)
- func (p *Provider) Output(ctx context.Context, h provider.Handle, s provider.Stream, off int64, ...) error
- func (p *Provider) Owner(_ context.Context, id string) (string, error)
- func (p *Provider) Preflight(_ context.Context, j *provider.JobSpec) error
- func (p *Provider) ResourceName(secret []byte, prefix, install, _, size, job string, expiry time.Time, _ int) string
- func (p *Provider) Spend(context.Context) (config.Micros, error)
- func (p *Provider) Start(_ context.Context, rt provider.Runtime) error
- func (p *Provider) SweepRules() provider.SweepPolicy
- func (p *Provider) Teardown(ctx context.Context, id string) error
- func (p *Provider) UseInstallSecret(b []byte)
- func (p *Provider) Watch(ctx context.Context, h provider.Handle, out provider.Sink) (provider.Result, error)
- type Rates
- type Resources
- type Session
- type Settings
- type Size
- type Sprite
- type TailExitError
Constants ¶
const DefaultAPIBase = "https://api.sprites.dev"
DefaultAPIBase is the production API. Tests use the fake's loopback URL only.
const MaxOutput = 8 << 20
MaxOutput bounds what Run keeps of stdout.
Variables ¶
var AgentSpec func(j *provider.JobSpec) agent.Spec
AgentSpec builds the agent's spec from the job; the orchestration sets it (as RunPod's).
var ErrNotFound = errors.New("sprites: not found")
ErrNotFound is matched (errors.Is) by every 404: a Sprite, a policy or a checkpoint that is not there. A 404 on a delete means done (sprites-provider.md 2.4).
var ErrNotProvisioned = errors.New("sprites: policies not verified before exec")
ErrNotProvisioned: a bitc bug, not an API answer. Exec refuses a Sprite this client created before its policies were set and verified (SP8), and Attach one whose job policy was not.
var ErrStreamEnded = &provider.ErrTransient{Why: "exec stream ended without an exit status"}
ErrStreamEnded: the exec connection ended without an exit status (a dropped socket, a Sprite gone cold, a close frame before the exit message).
Functions ¶
func AgentCmd ¶
AgentCmd is the argv of an agent exec through the J4 sha check (4, J4 step 1):
sh -c 'echo "<sha> /opt/bitc/bin/bitc" | sha256sum -c - >/dev/null && exec [sudo -n] /opt/bitc/bin/bitc __agent <args>'
sha is the agent's sha256 (not a secret). Every arg must be a plain word (job ids, file names, offsets, verbs and "--boot-stdin"), so nothing can reach the shell as syntax.
func EncodeName ¶
EncodeName is <prefix>-<install16>-<size>-<job8>-<E unix>-<tag8>, tag8 being the first 8 hex of HMAC(install secret, the name without "-tag8"). The pool is not in the name (no room).
func PreAttach ¶
PreAttach wraps a provider error class in ErrPreAttach for the Sprite id (the name): the resource exists and no job input reached it.
func ReadFrames ¶
ReadFrames decodes the NDJSON frames of `__agent tail` from r and calls fn for each, until the stream ends (nil) or fn returns an error. A line that is not a frame is an error.
func TokenOrg ¶
TokenOrg is the token's org slug: its first "/" field when that is lowercase letters, digits and dashes (at most 63, starting with a letter or digit); ok is false for any other token.
func VerifyName ¶
VerifyName reports whether the name's tag8 is the one this install's secret makes.
Types ¶
type AttachOptions ¶
AttachOptions: AgentSHA is the agent's sha256; Sudo is false when exec runs as root (probe 9.15); Deadline is D, from which max_run_after_disconnect = D + 10m - now is set; Payload is the framed boot payload (agent.BootPayload.Frame), sent on stdin and never in a URL.
type Checkpoint ¶
type Checkpoint struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Auto bool `json:"auto"`
}
Checkpoint is one checkpoint of a Sprite. Auto marks the platform's automatic ones.
type Cleaner ¶ added in v0.1.1
type Cleaner struct {
// contains filtered or unexported fields
}
Cleaner is the cleanup-only Sprites handle (config.Provider.CleanupOnly): Sprites jobs are refused in this release (#6), and `bitc sweep` may still list, owner-check and delete what 0.1.0 left. It is built from the API token and endpoint alone; no deploy key, env or job setting is read. It implements provider.Cleaner and SweepRules, nothing else.
func NewCleaner ¶ added in v0.1.1
NewCleaner builds the handle (provider.Factory.NewCleaner).
func (*Cleaner) List ¶ added in v0.1.1
List lists the Sprites under the prefixes (a transient failure is retried once).
func (*Cleaner) Owner ¶ added in v0.1.1
Owner is the owner tag of a Sprite whose name verifies under this install's secret, else "". It makes no API call: the tag is part of the name.
func (*Cleaner) SweepRules ¶ added in v0.1.1
func (c *Cleaner) SweepRules() provider.SweepPolicy
SweepRules are the provider's (one Sprite per job, no self-delete; the timer is required).
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to one Sprites org. It is safe for concurrent use.
func New ¶
New checks the options and returns a Client. The token is read from TokenFile when given.
func (*Client) ApplyBuildPolicies ¶
func (c *Client) ApplyBuildPolicies(ctx context.Context, name string, build NetworkPolicy, res Resources) error
ApplyBuildPolicies sets the build network policy and the resources policy of name and reads each back; they must match (PolicyMismatchError otherwise). Only then may the Sprite be exec'd (SP8): Exec refuses a Sprite this client created until this has succeeded.
func (*Client) ApplyJobPolicy ¶
ApplyJobPolicy replaces the network policy with the job policy and verifies it. The attach (Attach) of a Sprite this client created needs it.
func (*Client) Attach ¶
Attach starts `__agent --boot-stdin` and delivers the boot payload (J4). The error classes are the attach classification (1.3): an HTTP error status before 101 is ErrPreAttach (the class of the status, 1.2; the Sprite is the caller's to delete); a failure to connect at all (nothing sent) is ErrPreAttach{ErrTransient}; anything after the upgrade request was written (101, a timeout, a network error, a failed stdin write) is ErrAttached. A Sprite this client created must have its job policy verified first (ErrNotProvisioned).
func (*Client) CreateCheckpoint ¶
CreateCheckpoint takes a checkpoint of name (POST .../checkpoint). The answer may be one JSON object or NDJSON lines; the first object with an "id" is the checkpoint.
func (*Client) CreateSprite ¶
func (c *Client) CreateSprite(ctx context.Context, name string, labels map[string]string) (Sprite, error)
CreateSprite creates name with labels. It returns:
- the Sprite on 201;
- ErrTransient when nothing was created (429 and the quota codes, whatever their status);
- ErrPreAttach{ID: name} when a Sprite may exist: a 5xx, a network error or a timeout on the POST itself, a 409 (the name exists, left by an earlier attempt), or an org mismatch (the Sprite exists and the caller must delete it);
- ErrUnavailable for 401/402/403, ErrIneligible for other 4xx.
A 400 that blames the labels is retried once without them (labels are secondary, 2.1).
func (*Client) DeleteCheckpoint ¶
DeleteCheckpoint deletes one checkpoint; a 404 is ErrNotFound.
func (*Client) DeleteSprite ¶
DeleteSprite deletes name. nil means it is gone (204 or 404); any error means unconfirmed.
func (*Client) Exec ¶
Exec opens an exec session. Errors are the raw classes of 1.2: an upgrade refused with an HTTP status maps like any API answer (*wsmini.StatusError never escapes); a failure after the request was written is ErrTransient. Use Attach for the attach exec.
func (*Client) FSRead ¶
FSRead streams a file of the Sprite into w (GET .../fs/read?path=) and returns the byte count. Only ctx bounds it.
func (*Client) FSWrite ¶
FSWrite writes data to a file of the Sprite (PUT .../fs/write?path=, parents created).
func (*Client) GetCheckpoint ¶
GetCheckpoint reads one checkpoint; a 404 is ErrNotFound.
func (*Client) GetSprite ¶
GetSprite reads one Sprite; a 404 is ErrNotFound. An org mismatch returns the Sprite and an OrgMismatchError.
func (*Client) ListCheckpoints ¶
ListCheckpoints lists the checkpoints of name. Assumed (probe 9.1): the list includes the automatic ones, which is the worst case for the secrecy tests.
func (*Client) ListConnections ¶
ListConnections lists the org's Connectors (OAuth connections) by name, `GET /v1/oauth/connections`.
The answer's shape is unverified (probe 9.9): a JSON array, or an object holding one under "connections", "items" or "data"; an element is a string or an object with a "name", "id" or "provider". Only the names are used, sorted.
func (*Client) ListSprites ¶
ListSprites lists every Sprite whose name starts with prefix (the API cannot filter by label), following the continuation token to the end. A page repeating the token, or more than 1000 pages, is an error. Any Sprite of another org fails the list (OrgMismatchError, the Sprite named). The result is sorted by name.
func (*Client) Organization ¶
Organization reads GET /v1/organization.
func (*Client) Raw ¶
func (c *Client) Raw(ctx context.Context, method, path string, q url.Values, body any) (int, []byte)
Raw sends one bounded JSON request to a /v1/ path and returns the status (0 for no answer, and for a path outside /v1/ or with a dot-dot) and the body. It is the probe kit's way to try an endpoint or a body the typed methods do not know.
func (*Client) Read ¶
func (c *Client) Read(ctx context.Context, name, agentSHA, job, file string, off int64, w io.Writer) (int, error)
Read streams `__agent read <job> <file> <off>` into w and returns the agent's exit status (0 ok, 64 bad argument, 65 offset past the end, 66 not found, 69 agent error).
func (*Client) RestoreCheckpoint ¶
RestoreCheckpoint restores name to the checkpoint.
func (*Client) Run ¶
func (c *Client) Run(ctx context.Context, name string, r ExecRequest, stdin []byte) (ExecResult, error)
Run execs r, sends stdin (when r.Stdin) and collects the result. It is for provisioning commands and small reads; use Exec, Tail or Read for streams.
func (*Client) Tail ¶
func (c *Client) Tail(ctx context.Context, name, agentSHA, job string, offs map[string]int64, fn func(agent.Frame) error) error
Tail opens `__agent tail <job> <agent> <out> <err>` through the sha check and calls fn for each frame until the agent's final done frame, the end of the stream, or an error. A stream that ends before the done frame returns ErrStreamEnded (the caller reopens from the last offsets).
type ExecRequest ¶
ExecRequest is one exec. Cmd is the argv (no secret: it travels in the URL). Stdin opens the stdin channel. MaxRunAfterDisconnect, when set, lets the process outlive the connection for that long (assumed absent = it dies with the connection).
type ExecResult ¶
type ExecResult struct {
Exit int
Stdout []byte // at most MaxOutput
Stderr []byte // the last 64 KiB
}
ExecResult is a finished exec.
type NetRule ¶
NetRule is one network policy rule: an explicit domain (exact or "*.d") and an action.
type NetworkPolicy ¶
type NetworkPolicy struct {
Rules []NetRule `json:"rules"`
}
NetworkPolicy is a list of allowed domains. There is no "include" and no "*" (design decision 4).
func AllowDomains ¶
func AllowDomains(domains ...string) (NetworkPolicy, error)
AllowDomains builds an allow-only policy from explicit domains, sorted and de-duplicated.
type NotFoundError ¶
type NotFoundError struct{ What string }
NotFoundError is the 404 answer to an API request.
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
func (*NotFoundError) Is ¶
func (e *NotFoundError) Is(t error) bool
type Options ¶
type Options struct {
APIBase string // default DefaultAPIBase; http only for a loopback host
Org string // required; the token's org slug must equal it
Token string
TokenFile string // a 0600 file owned by the user or root; read once, never logged
HTTP *http.Client
// Timeout bounds one REST request (default 30s). HandshakeTimeout bounds the wait for the
// exec upgrade answer (default 30s).
Timeout, HandshakeTimeout time.Duration
// NoSudo drops `sudo -n` from every agent exec (tail, read, the attach), for a Sprite whose
// exec user is root already (probe 9.15). The default runs the agent through sudo.
NoSudo bool
}
Options configure a Client. Exactly one of Token and TokenFile is set.
type OrgInfo ¶
type OrgInfo struct {
Slug string
Raw json.RawMessage
}
OrgInfo is the answer of GET /v1/organization: the slug (the first of "slug", "name", "id" or "organization" that is a string) and the whole body.
type OrgMismatchError ¶
type OrgMismatchError struct {
Name, Got, Want string
}
OrgMismatchError: a Sprite response names an organization other than the configured one (design decision 11). It is an ErrUnavailable (one pause record): errors.As finds a *provider.ErrUnavailable in it. The caller deletes the Sprite at once.
func (*OrgMismatchError) As ¶
func (e *OrgMismatchError) As(target any) bool
As lets errors.As(err, &*provider.ErrUnavailable) match.
func (*OrgMismatchError) Error ¶
func (e *OrgMismatchError) Error() string
func (*OrgMismatchError) ForeignOrg ¶
func (e *OrgMismatchError) ForeignOrg() (string, string)
ForeignOrg names the Sprite and its organization (provider.ForeignOrg): the sweep, doctor and status report it and never touch it.
func (*OrgMismatchError) PausesAfterAttach ¶
func (e *OrgMismatchError) PausesAfterAttach() bool
PausesAfterAttach: a guard hit after the attach still pauses the provider (design 6.1): the job is 75 as usual, and the one pause record keeps the next job from creating in a wrong org.
type OrgTokenError ¶
OrgTokenError: the token's org slug differs from the configured org, or it carries none. The slug is printed only when the token has the "<slug>/<rest>" shape with a slug-shaped first field (TokenOrg), because any other token (a Fly macaroon is base64, "/" included) would otherwise be printed in part or whole.
func (*OrgTokenError) Error ¶
func (e *OrgTokenError) Error() string
type PolicyMismatchError ¶
type PolicyMismatchError struct{ Name, Policy string }
PolicyMismatchError: a policy read back after it was set differs from what was set. The platform did not take it, so nothing may be exec'd; it is transient (retry on a fresh Sprite).
func (*PolicyMismatchError) As ¶
func (e *PolicyMismatchError) As(target any) bool
func (*PolicyMismatchError) Error ¶
func (e *PolicyMismatchError) Error() string
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider is the Sprites provider (sprites-provider.md, phase 1: a fresh Sprite per job).
func NewProvider ¶
NewProvider builds the provider from its host section.
func (*Provider) DoctorLines ¶
func (p *Provider) DoctorLines(ctx context.Context) []provider.DoctorLine
DoctorLines are the provider's own `doctor --remote` checks (sprites-provider.md 6.1, 5.2): the org guard over every Sprite of the org, Connectors, Sprites outside name_prefix, and more than one install holding Sprites (daily_usd is a per-host share).
func (*Provider) Fetch ¶
func (p *Provider) Fetch(ctx context.Context, h provider.Handle, a provider.ArtifactSpec, w io.Writer) error
Fetch downloads artifacts.tar.gz from a.Offset over exec, capped (resumable by offset).
func (*Provider) Launch ¶
Launch makes the job's Sprite, provisions it and attaches (sprites-provider.md 4, J2-J4):
create; build and resources policies, each read back; the agent installed by exec; `__agent provision` (packages and tools); the job policy, read back; then the attach exec, the first and only thing that carries job input.
Everything before the attach is job-neutral, so every failure up to it is an ErrPreAttach naming the Sprite (the core deletes it and applies the fallback boundary); a failure to create that is not ambiguous is a plain error class. Once the attach was sent, nothing falls back.
func (*Provider) List ¶
List lists the Sprites whose names start with a prefix. A transient failure is retried once.
func (*Provider) Output ¶
func (p *Provider) Output(ctx context.Context, h provider.Handle, s provider.Stream, off int64, w io.Writer) error
Output copies a result file from off (spec 8.4 "Host side"), over exec.
func (*Provider) Owner ¶
Owner returns the owner tag of a Sprite this install made, "" for any other: the proof is in the name (sprites-provider.md 2.1), so no request is made. The value is what provider.OwnerMatches compares.
func (*Provider) ResourceName ¶
func (p *Provider) ResourceName(secret []byte, prefix, install, _, size, job string, expiry time.Time, _ int) string
ResourceName is the Sprite name of a job (provider.Namer): the owner tag is part of it.
func (*Provider) Spend ¶
Spend: Sprites has no billing API (Caps.Spend is false), so the cap relies on the ledger.
func (*Provider) Start ¶
Start keeps the host's redactor, so the deploy key joins it (Walk calls Start once).
func (*Provider) SweepRules ¶
func (p *Provider) SweepRules() provider.SweepPolicy
SweepRules: one Sprite per job, no self-delete (sprites-provider.md 2.4, decision 8). An own Sprite with no live reservation is deleted once it is older than start_timeout.
func (*Provider) UseInstallSecret ¶
UseInstallSecret sets the secret directly (tests).
func (*Provider) Watch ¶
func (p *Provider) Watch(ctx context.Context, h provider.Handle, out provider.Sink) (provider.Result, error)
Watch follows the job until its EXIT marker and the end of the agent (spec 8.4 host side). A dropped tail is not an error: it is reopened from the last offsets, and when reopening fails twice within 30 s the files are read every 5 s until a reopen succeeds.
type Resources ¶
type Resources struct {
LimitMB int `json:"limit_mb"`
}
Resources is the memory policy: a limit in MiB, never autoscaled.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is one live exec. Read Stdout until EOF (or Close); Wait returns the exit status.
func (*Session) Close ¶
Close drops the connection (the process may live on, per MaxRunAfterDisconnect) and ends Stdout.
func (*Session) CloseStdin ¶
CloseStdin sends the stdin EOF (once).
func (*Session) Stdout ¶
Stdout is the process's stdout. Backpressure applies: the session stops reading the socket while Stdout is not read.
type Settings ¶
type Settings struct {
Org, APIBase string
Sizes map[string]Size
Rates Rates
DiskBound, MemoryBound config.Size
EgressAllow, EgressBuildAllow []string
}
Settings are the provider-specific keys of [providers.sprites] (sprites-provider.md 7).
func DecodeSettings ¶
DecodeSettings decodes the provider-specific keys strictly. The messages come back in key order, each as the text after `providers.sprites.`; namePrefix is the core name_prefix, which bounds the size keys (resource names stay within 63 characters).
func (Settings) EstimateFor ¶
EstimateFor is the price of size over d.
type Size ¶
type Size struct {
Memory config.Size
USDPerHour config.Micros // the computed price, raised to the host's usd_per_hour when that is higher
}
Size is one entry of [providers.sprites.sizes].
type Sprite ¶
type Sprite struct {
ID string `json:"id"`
Name string `json:"name"`
Organization string `json:"organization"`
Status string `json:"status"` // cold | warm | running
CreatedAt time.Time `json:"created_at"`
Labels map[string]string `json:"labels,omitempty"`
}
Sprite is the API's view of a Sprite. Organization is checked on every response.
type TailExitError ¶
type TailExitError struct{ Code int }
TailExitError: `__agent tail` ended with a nonzero exit status (66: the job's directory is not there yet, which the first tail after the attach can meet). It is transient.
func (*TailExitError) As ¶
func (e *TailExitError) As(target any) bool
func (*TailExitError) Error ¶
func (e *TailExitError) Error() string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package liveprobe is the Sprites probe kit: a scripted, capped runner that answers the open items of docs/design/sprites-provider.md section 9 against the live Sprites API.
|
Package liveprobe is the Sprites probe kit: a scripted, capped runner that answers the open items of docs/design/sprites-provider.md section 9 against the live Sprites API. |
|
Package spritesfake is a strict fake of the Fly Sprites API for tests (sprites-provider.md 8.1): an httptest REST server plus a WSS exec endpoint.
|
Package spritesfake is a strict fake of the Fly Sprites API for tests (sprites-provider.md 8.1): an httptest REST server plus a WSS exec endpoint. |