provider

package module
v0.0.0-...-e43c196 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 23 Imported by: 2 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.

README

Provider packages: manifest and protocol reference (S472.14)

Version: provider/v1 (the only protocol version this module speaks). Module: github.com/qiangli/yoke/pkg/provider — a nested stdlib-only module importable by Go 1.26. New code under pkg/provider imports only the standard library and other pkg/provider packages.

A provider package provisions host/VM infrastructure. It has one of two forms. Both speak the same Request/Result schema; they differ only in where the behavior runs.

  • declarative: data only (endpoints, request templates, lifecycle mapping), interpreted by the built-in engine. The master runs it with exec disabled. Authoring and validation need no local machine.
  • executable: an argv-invoked program. The Request goes as one JSON document on stdin, one Result comes back on stdout, diagnostics go to stderr. It runs only on user-owned compute (local bashy or an existing satellite). The master never executes user code.

kind is always infra (fleet kind and bashy verb of record, S472.0).

Manifest

field declarative executable notes
kind infra infra required
name string string required, unique in the ring
form declarative executable required
version string string optional, informational
protocol_version provider/v1 provider/v1 required, must match exactly
summary string string optional
capabilities op list op list required; one capability names one operation
argv absent command line exec'd directly, never through a shell
declarative document below absent schema owned by the engine
builtin marker n/a loader-level only (fleet): a compiled-in reference entry dispatched to the linked-in Go adapter, never the engine

Capabilities name lifecycle operations: validate, capacity, plan, create, inspect, list, start, stop, destroy, plus the optional reboot, resize and the feature flags volumes, spot. An operation outside the manifest is refused with unsupported_capability before any provider call. Every Op is also a capability; plan is rendered locally and takes no endpoint.

Credentials are never manifest fields. They are references resolved by the caller at open (once, held in memory, scrubbed from journals and logs), placed on the wire only as the manifest's auth declares.

Declarative document

base_url: https://api.example.com
auth: {in: header, name: Authorization, value: "Bearer ${credential}"}
headers: {X-Owner: "${owner_tag}"}
resource: {id: id, name: name, status: status, region: region,
  size: size, tags: tags, public_ips: ips, created_at: created_at,
  retained: retained}
states: {new: pending, running: running, stopped: stopped, deleted: deleted}
operations:
  validate: {method: GET, path: /api/account}
  capacity: {method: GET, path: /api/regions}
  create: {method: POST, path: /api/machines, result: machine,
    body: {name: "${name}", region: "${spec.region}",
      size: "${spec.size}", image: "${spec.image}", tags: "${tags}"}}
  inspect: {method: GET, path: "/api/machines/${resource_id}", result: machine}
  list: {method: GET, path: /api/machines, result: machines}
  start: {method: POST, path: "/api/machines/${resource_id}/power",
    body: {action: start}, result: machine}
  stop: {method: POST, path: "/api/machines/${resource_id}/power",
    body: {action: stop}, result: machine}
  destroy: {method: DELETE, path: "/api/machines/${resource_id}", result: machine}

Rules the engine enforces at registration (ValidateDeclarative — the same function the master calls, so registration and the engine agree):

  • base_url is http(s); auth.in is header or query; auth.value must place ${credential} (default "${credential}").
  • ${credential} appears nowhere else: not in headers, paths, query, result or bodies.
  • resource.id, resource.status and resource.tags are required; paths are dot-separated keys (array indexes are digits), no functions.
  • Every declared capability except plan has an endpoint with a valid method and a /-rooted path; create needs list (idempotent create looks the resource up by its tag). Unknown fields are rejected.
  • Templates are pure substitution (${field} from a closed placeholder set: credential, resource_id, idempotency_key, idempotency_tag, owner_tag, name, tags, spec.name, spec.region, spec.size, spec.image, spec.user_data). An unknown placeholder is an error. Nothing is evaluated: no functions, no shell.

The engine keeps the reference discipline: every created resource carries the bashy-lease tags (lease marker, owner, hashed idempotency key, temporary marker when authorized); a replayed create finds its resource by tag instead of allocating another; an existing resource is acted on only when it carries this owner's tags.

Executable protocol

argv[0] is exec'd directly with the JSON Request on stdin:

{"protocol_version": "provider/v1", "op": "create",
 "idempotency_key": "boot-1", "spec": {"name": "sat", "region": "r1"}}

and answers one JSON Result on stdout:

{"protocol_version": "provider/v1", "op": "create",
 "resource": {"id": "mach-1", "name": "sat", "state": "running"}}

Every hook — validate, capacity, plan, create, inspect, list, start, stop, destroy — follows this shape. Failures are normalized {"error": {"code": "...", "message": "..."}} results (see below). A result whose op differs from the request's is refused with protocol_mismatch, so a plugin cannot substitute one operation for another. Mutating ops require an idempotency key; inspect, start, stop, destroy (and reboot/resize) require a resource ID.

Errors, identity, authorization, billing

Normalized error codes: unsupported_capability, confirmation_required, not_owned, not_found, invalid_request, invalid_credentials, protocol_mismatch, rate_limited, timeout, provider_error, needs_manual_reconcile, exec_disabled. Every adapter reports a failure in Result.Error and returns it as the Go error, so callers may use either channel.

Operation identity: one idempotency key names one operation on one resource. Replaying a key answers from the journal without acting again; carrying a key to another resource is refused. A create whose answer is lost is reconciled by idempotency tag before any retry, so at most one resource results.

A replayed CREATE is the one answer that is proven before it is served: its resource is inspected first, because the resource may have been destroyed since (here with another key, by a TTL sweep, or in the provider's own console) and replaying the old result would report a host that does not exist while making no provider call at all. A resource that is gone retires the journal entry (phase retired, append-only like every other record) and the key creates anew; a live one is reported with its CURRENT state; an inspect that merely fails proves nothing and the journal's answer stands. A successful destroy retires the create entries of the resource it removed.

Destroy authorization (amendment A6): destroying a persistent resource needs a per-operation confirmation bound to exactly that resource ID and that idempotency key; without it the destroy is refused before any provider call and the resource keeps its ongoing cost. A confirmation is single use by construction. A temporary resource (TTL or work-bound authorization recorded at create and tagged on the resource) is destroyed under that authorization with no confirmation; a temporary authorization on a resource not created as temporary is refused.

Stop versus destroy: stop powers the resource off — state stopped, data retained, billing ongoing until destroyed. Stop never deletes; a stop that reports deleted is a destroy on the stop path and fails conformance. Destroy reports deleted plus what is retained (and still billed).

Paths: cloud-only and executable

Both paths are described only in terms of the public dhnt.io protocol: access registration first, then the dhnt.io satellite provisioning workflow. The two-stage example: create the host with the provider, then the satellite installs its proprietary artifact from dhnt.io.

  • Cloud-only (declarative): author a declarative manifest (no local machine needed), register it at dhnt.io, provision there. The manifest is validated at registration by ValidateDeclarative and runs on the built-in engine with exec disabled. Validation status is shown; dhnt certification is not a gate. Sharing via Git or a local directory needs no hosted registry.
  • Executable: register locally, run from local bashy or an existing satellite (user-owned compute only). The master never runs it.

Authoring and conformance

  • infra init --form declarative|executable --name NAME --dir DIR writes the scaffold: manifest (+ executable skeleton implementing every standard hook for the executable form), config.example.json and deterministic fixtures.
  • infra validate [DIR] checks schema, capabilities, structured errors, timeout handling and operation identity without allocating anything. The declarative check is ValidateDeclarative, the same function the master calls at registration.
  • pkg/provider/conformance is the reusable suite both forms must pass: states and transitions, idempotency and reconciliation, normalized errors, unsupported operations, stop-versus-destroy billing and data semantics, and A6 destroy confirmation. Fixture-only by default (WithLive(auth) enables the allocating lifecycle); never touches the network beyond httptest.

Built-in adapters

Two providers ship linked in (FormBuiltin): neither is dispatched to the declarative engine and neither spawns a program.

  • digitalocean (S472.4a) is the REFERENCE example: droplets over the v2 API, the smallest adapter that passes conformance.
  • aws (S522.2) is Lightsail over the Lightsail JSON API. What it adds beyond the reference shape, because AWS needs it:
    • a stdlib SigV4 signer (sigv4.go), pinned by AWS's published SigV4 test-suite vectors. This module is stdlib-only, so there is no AWS SDK here and no pkg/provider package may add one.
    • a budget preflight before every create (budget.go for the policy, budgets.go for the spend ladder): the bundle's monthly price plus the account's month-to-date spend BEFORE CREDITS must stay within the operator's monthly cap, and the bundle price within the per-instance ceiling. Spend comes from the account's own AWS BUDGET first (DescribeBudget's CalculatedSpend.ActualSpend, with BudgetLimit as the cap when none is given) and Cost Explorer (GetCostAndUsage, Not/RECORD_TYPE=Credit) second — because Cost Explorer cannot answer at all on an account whose cost data has never been ingested. It FAILS CLOSED: when NEITHER source can be read, spend is unknown and the create is refused. No GPU, ever.
    • governance tags on top of the bashy-lease tags: dhnt:managed=true always, plus dhnt:sprint / dhnt:story / dhnt:ttl. The automation IAM policy permits deleting only dhnt:managed=true resources, so destroy refuses an untagged instance up front rather than failing as an opaque AccessDeniedException.
    • lossless user-data delivery (userdata.go, s3.go): the master's first-boot script reaches the host byte-identical, through whichever of three layers it fits in — raw; gzip+base64 inside a tiny #!/bin/sh bootstrap when it exceeds EC2's 16 KiB launch limit (which Lightsail inherits); or, when even that does not fit, staged in S3 and fetched at first boot by a few-hundred-byte bootstrap over a SigV4 query-PRESIGNED GET, which verifies the script's sha256 before running it. The live script is ~43 KB and ~21.7 KB compressed, so the third layer is the one in use; the object key is recorded as the dhnt:userdata-key tag (the IAM policy grants no s3:ListBucket, so a later destroy has no other way to find it). Nothing is ever truncated.
    • a static IP named <instance>-ip, allocated and attached at create so the satellite's endpoint survives a stop/start, reported by inspect, and released by destroy (an unattached Lightsail static IP is billed).
    • the satellite firewall, replacing the instance's public ports with tcp 80/443/6443/10250, udp 8475-8476 and tcp 22 restricted to the lightsail-connect CIDR alias — a mirror of the DigitalOcean dhnt-satellite firewall.

Which names are built in, their per-provider --region/--size/--image defaults and how each is opened all live in ONE place outside this module: pkg/fleet/infra_builtin.go. bashy infra provision carries no per-provider branching; the provider is named positionally (infra provision aws) or with --provider aws.

Note a Lightsail resource is addressed by NAME, so Resource.ID is the instance name; nothing in the contract requires an opaque id.

Future work (blocks nothing)

Maintained EC2/GCP/Azure/Lambda adapters and Runpod container-worker semantics are future work; dhnt certification of third-party providers is not a gate.

Documentation

Overview

Package provider is the versioned host/VM provider contract (S472).

A provider package is either a declarative manifest (data only, run by the built-in engine) or an executable plugin (argv-invoked, JSON over stdin/stdout, diagnostics on stderr). Both speak the same Request/Result schema below. This file freezes the shared types so the contract, loader and dispatcher stories can proceed in parallel; behavior lives elsewhere.

Endpoint reservation (S522.2 rework 3).

A satellite's public endpoint has to be known BEFORE the host exists. The master renders the first-boot script with the endpoint baked into it, and a script that discovers its own address from cloud metadata works only on the one cloud whose metadata format it knows — which is exactly how the first zoo-aws create came up without ever enrolling.

So a provider that can hold a stable address reserves it FIRST, the reserved address becomes the enrollment bundle's endpoint hint, and the host is created afterwards and attached to the address it was already told about. Nothing then depends on metadata, and nothing races the attachment against first boot.

Reservation is an OPTIONAL capability, deliberately kept OFF the Adapter interface: a provider with no stable addresses stays exactly as it was and the provisioning sequence simply has no hint to send, rather than every adapter having to grow a method that answers "not me".

Index

Constants

View Source
const (
	PhCredential     = "credential"
	PhResourceID     = "resource_id"
	PhIdempotencyKey = "idempotency_key"
	PhIdempotencyTag = "idempotency_tag"
	PhOwnerTag       = "owner_tag"
	PhName           = "name"
	PhTags           = "tags" // JSON array in a body; comma-joined elsewhere
	PhSpecName       = "spec.name"
	PhSpecRegion     = "spec.region"
	PhSpecSize       = "spec.size"
	PhSpecImage      = "spec.image"
	PhSpecUserData   = "spec.user_data"
)

Placeholders accepted in templates. ${credential} is accepted only in Auth.Value, so a document cannot route the credential into a body, a path or a query parameter by another name.

View Source
const (
	// TagLease marks a resource as created through this contract.
	TagLease = "bashy-lease"
	// TagTemporary marks a resource created with a temporary-lifecycle
	// authorization (A6); only such a resource may be destroyed under one.
	TagTemporary = "bashy-temp"
)

The bashy-lease tag discipline: the tags on a provider resource are the durable record of who owns it, which request created it and whether it was created as temporary. They survive the controller (a fresh process, or a lost create response, can recover everything from the provider), so adapters must write them at create and read them back before acting.

Every tag fits the common provider tag charset [A-Za-z0-9_:-], max 255.

View Source
const GiB int64 = 1 << 30

GiB is one gibibyte in bytes.

View Source
const KindInfra = "infra"

KindInfra is the Manifest.Kind of every provider package (the fleet kind and bashy verb of record are both "infra", S472.0).

View Source
const ProtocolVersion = "provider/v1"

ProtocolVersion is the only protocol version this package speaks.

Variables

This section is empty.

Functions

func DeadlineFromTags

func DeadlineFromTags(tags []string) (time.Time, bool)

DeadlineFromTags returns the latest recorded deadline, if any.

func DeadlineTag

func DeadlineTag(t time.Time) string

DeadlineTag records a TTL. When several are present the latest wins (DeadlineFromTags), which is how a lease is extended.

func DefaultJournalDir

func DefaultJournalDir() (string, error)

DefaultJournalDir is where the local journal lives: BASHY_HOME/provider/ journal, with BASHY_HOME defaulting to $HOME/.bashy.

func Expand

func Expand(tmpl string, vars map[string]string) (string, error)

Expand substitutes ${field} placeholders in tmpl from vars. An unknown placeholder is an error: templates are closed, nothing is evaluated.

func IdempotencyTag

func IdempotencyTag(key string) string

IdempotencyTag is the tag recording the idempotency key of the create that made a resource. Keys are hashed, so any key string is safe.

func LeaseTags

func LeaseTags(owner, idempotencyKey string, temp *Authorization) []string

LeaseTags returns the tags a create must write: lease, owner, idempotency key and, for a temporary authorization, the temporary marker plus its deadline and/or work tag.

func Owned

func Owned(tags []string, owner string) bool

Owned reports whether tags carry the lease and owner's tags.

func OwnerTag

func OwnerTag(owner string) string

OwnerTag is the ownership tag for an owner; an adapter acts on an existing resource only when it carries TagLease and its owner's tag. owner must satisfy ValidOwner.

func Serve

func Serve(ctx context.Context, a Adapter, r io.Reader, w io.Writer) error

Serve is the plugin side of the executable protocol: it reads one Request from r, runs it on a, and writes one Result to w. A plugin's main is typically `provider.Serve(ctx, adapter, os.Stdin, os.Stdout)` with diagnostics on os.Stderr. A normalized failure is a Result, not a Serve error; Serve fails only when it cannot read the request or write the result.

func SslipEndpoint

func SslipEndpoint(ip string) string

SslipEndpoint is the https endpoint an IPv4 address answers on through sslip.io, the wildcard DNS service that resolves an address written into its own domain straight back to that address: 52.12.110.80 becomes https://52-12-110-80.sslip.io.

The DASHED spelling is the one used, not the dotted one: a dotted address is several DNS labels deep under sslip.io and a wildcard certificate covers exactly one label, so only the dashed form gets built-in TLS.

It returns "" for anything that is not an IPv4 address: an IPv6 address has no dashed form here, and a host name needs no hint.

func TemporaryKey

func TemporaryKey(createKey string) string

TemporaryKey is the idempotency key of the automatic destroy of a temporary resource created under createKey: deterministic, so expiry sweeps and work completion destroy it exactly once.

func ValidOwner

func ValidOwner(owner string) bool

ValidOwner reports whether owner can be used verbatim in OwnerTag.

func ValidateDeclarative

func ValidateDeclarative(m Manifest) error

ValidateDeclarative validates a declarative manifest against the engine schema without evaluating anything or making any network call. It is the same function the master calls at registration.

func ValidateManifest

func ValidateManifest(m Manifest) error

ValidateManifest checks a manifest's identity, protocol version, form and capability set.

func WorkTag

func WorkTag(ref string) string

WorkTag records the work a work-bound temporary resource belongs to. A ref that is not tag-safe is hashed.

Types

type Accelerator

type Accelerator struct {
	Vendor      string  `json:"vendor,omitempty"`
	Model       string  `json:"model"`
	MemoryBytes int64   `json:"memory_bytes"`
	Fraction    float64 `json:"fraction,omitempty"`
	Unified     bool    `json:"unified,omitempty"`
}

Accelerator is one accelerator device. MemoryBytes is that device's own memory (for a fractional device, its slice). Fraction is the share of a physical device (1 = whole). Unified marks memory shared with the host.

type Adapter

type Adapter interface {
	Manifest() Manifest
	Do(ctx context.Context, req Request) (Result, error)
}

Adapter executes contract requests for one provider. Built-in adapters, the declarative engine and the executable-plugin runner all implement it.

func Guard

func Guard(a Adapter) Adapter

Guard wraps an adapter so every request is checked by CheckRequest before the adapter runs. A refused request never reaches the adapter. Guard also refuses a result whose op differs from the request's, so an adapter cannot substitute one operation for another.

func NewDeclarativeAdapter

func NewDeclarativeAdapter(m Manifest, cfg DeclarativeConfig) (Adapter, error)

NewDeclarativeAdapter returns the engine for a declarative manifest, wrapped in Guard. It makes no network call until Do.

func NewExecAdapter

func NewExecAdapter(m Manifest, opts ExecOptions) (Adapter, error)

NewExecAdapter returns the runner for an executable provider plugin. Each Do execs m.Argv directly (never through a shell), writes the Request as one JSON document on stdin, and reads one Result from stdout; stderr carries diagnostics only. The runner is wrapped in Guard, so an undeclared operation, a missing idempotency key or an unauthorized destroy is refused without executing the plugin.

type Allocation

type Allocation struct {
	Accelerators []Accelerator `json:"accelerators,omitempty"`
	ObservedAt   time.Time     `json:"observed_at,omitempty"`
}

Allocation is what is actually allocated/observed on a host, distinct from what the catalog advertises. Nil means nothing observed.

type AuthKind

type AuthKind string

AuthKind is the kind of destroy authorization (S450.1 amendment A6).

const (
	// AuthConfirmation is a single-use user confirmation bound to one
	// resource ID and one idempotency key.
	AuthConfirmation AuthKind = "confirmation"
	// AuthTemporary is a temporary-lifecycle authorization (TTL or
	// work-bound) recorded at create and tagged on the resource.
	AuthTemporary AuthKind = "temporary"
)

type Authorization

type Authorization struct {
	Kind           AuthKind  `json:"kind"`
	ResourceID     string    `json:"resource_id,omitempty"`
	IdempotencyKey string    `json:"idempotency_key,omitempty"`
	ExpiresAt      time.Time `json:"expires_at,omitempty"` // TTL form
	WorkRef        string    `json:"work_ref,omitempty"`   // work-bound form
}

Authorization accompanies destroy requests (and, for AuthTemporary, the create that recorded it).

type AvailState

type AvailState string

AvailState is whether an offer can currently be bought.

const (
	AvailAvailable   AvailState = "available"
	AvailUnavailable AvailState = "unavailable"
	AvailUnknown     AvailState = "unknown"
)

type Availability

type Availability struct {
	State      AvailState `json:"state"`
	Reason     string     `json:"reason,omitempty"`
	ObservedAt time.Time  `json:"observed_at,omitempty"`
}

Availability is the (advertised) availability in the offer's region.

type BuiltinFactory

type BuiltinFactory func(ctx context.Context, m Manifest, credential string) (Adapter, error)

BuiltinFactory builds a built-in adapter for a manifest from the credential the dispatcher resolved. Hosts register one per built-in provider name (e.g. digitalocean.New behind "digitalocean").

type CPU

type CPU struct {
	Arch  string `json:"arch,omitempty"`
	Count int    `json:"count"`
}

CPU is the host CPU shape.

type Capability

type Capability string

Capability names an operation or optional feature a provider declares. Every Op is also a capability; "volumes" and "spot" are feature flags.

const (
	CapVolumes Capability = "volumes"
	CapSpot    Capability = "spot"
)

type Charge

type Charge struct {
	Known      bool      `json:"known"`
	USD        float64   `json:"usd,omitempty"`
	ObservedAt time.Time `json:"observed_at,omitempty"`
}

Charge is one projected cost line; Known=false is an explicit unknown.

type CostPlan

type CostPlan struct {
	Compute  Charge   `json:"compute"`
	Storage  Charge   `json:"storage"`
	Network  Charge   `json:"network"`
	Measured *float64 `json:"measured_usd,omitempty"`
}

CostPlan separates quoted (projected) from measured (nil until observed).

type CostReport

type CostReport struct {
	Ongoing  bool     `json:"ongoing"`
	Retained []string `json:"retained,omitempty"`
	Note     string   `json:"note,omitempty"`
}

CostReport describes what keeps costing money after stop or a refused / partial destroy (retained disks, reserved IPs, the instance itself).

func RefusedDestroyCost

func RefusedDestroyCost() *CostReport

RefusedDestroyCost is the cost report attached to a refused destroy: the resource was not touched, so whatever it cost before it still costs.

type CredentialFunc

type CredentialFunc func(ctx context.Context, provider string) (string, error)

CredentialFunc adapts a function to CredentialSource.

func (CredentialFunc) Credential

func (f CredentialFunc) Credential(ctx context.Context, provider string) (string, error)

Credential implements CredentialSource.

type CredentialSource

type CredentialSource interface {
	Credential(ctx context.Context, provider string) (string, error)
}

CredentialSource resolves the provider credential. It is the one seam between this stdlib-only package and the host's credential store.

type DeclarativeAuth

type DeclarativeAuth struct {
	// In is "header" or "query".
	In string `json:"in"`
	// Name is the header or query parameter.
	Name string `json:"name"`
	// Value is a template that must use ${credential} (default:
	// "${credential}"; e.g. "Bearer ${credential}").
	Value string `json:"value,omitempty"`
}

DeclarativeAuth says where the credential goes on each request.

type DeclarativeConfig

type DeclarativeConfig struct {
	// Credential is held in memory only; it is placed as Auth declares
	// and never written anywhere.
	Credential string
	// Owner scopes ownership (ValidOwner).
	Owner string
	// HTTPClient defaults to a client with a 60s timeout.
	HTTPClient *http.Client
}

DeclarativeConfig configures the engine for one provider.

type DeclarativeDoc

type DeclarativeDoc struct {
	// BaseURL is the API root every operation path is joined to.
	BaseURL string `json:"base_url"`
	// Headers are sent on every request (templated; the credential is
	// not allowed here — see Auth).
	Headers map[string]string `json:"headers,omitempty"`
	// Auth places the credential.
	Auth DeclarativeAuth `json:"auth"`
	// Resource maps a provider resource object onto the normalized
	// Resource (JSON paths relative to the operation's Result).
	Resource DeclarativeResource `json:"resource"`
	// States maps the provider's raw status strings onto normalized
	// states; anything unmapped is StateUnknown.
	States map[string]State `json:"states"`
	// Operations declares one endpoint per supported Op. The manifest's
	// capability list must match its keys (plan needs no endpoint).
	Operations map[Op]*DeclarativeEndpoint `json:"operations"`
}

DeclarativeDoc is the declarative document a Manifest.Declarative decodes into.

func ParseDeclarative

func ParseDeclarative(m Manifest) (*DeclarativeDoc, error)

ParseDeclarative decodes and validates m.Declarative.

type DeclarativeEndpoint

type DeclarativeEndpoint struct {
	Method string `json:"method"`
	// Path is a template joined to BaseURL.
	Path string `json:"path"`
	// Query holds templated query parameters.
	Query map[string]string `json:"query,omitempty"`
	// Body is a JSON template: every string value is expanded, and a
	// string that is exactly "${tags}" becomes the JSON array of tags.
	Body json.RawMessage `json:"body,omitempty"`
	// Result is the JSON path of the resource object (or, for list, the
	// array of them) in the response. Empty means the whole body; for
	// operations whose response carries no resource (a 204 destroy, an
	// action receipt) set NoResource.
	Result string `json:"result,omitempty"`
	// NoResource says the response does not describe the resource; the
	// engine inspects it afterwards (or, for destroy, reports it deleted).
	NoResource bool `json:"no_resource,omitempty"`
}

DeclarativeEndpoint is one operation's HTTP call.

type DeclarativeResource

type DeclarativeResource struct {
	ID        string `json:"id"`
	Name      string `json:"name,omitempty"`
	Status    string `json:"status"`
	Region    string `json:"region,omitempty"`
	Size      string `json:"size,omitempty"`
	Tags      string `json:"tags"`
	PublicIPs string `json:"public_ips,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
	// Retained lists what the provider keeps (and bills) after the
	// resource is destroyed or stopped, e.g. attached volumes.
	Retained string `json:"retained,omitempty"`
}

DeclarativeResource maps a resource object's JSON paths. ID, Status and Tags are required; the others are optional. Paths are dot-separated keys (array indexes are digits), no functions.

type DeviceComparison

type DeviceComparison struct {
	Known      bool             `json:"known"`
	Advertised int              `json:"advertised"`
	Observed   int              `json:"observed"`
	Mismatches []DeviceMismatch `json:"mismatches,omitempty"`
}

DeviceComparison is the result of CompareAccelerators.

func CompareAccelerators

func CompareAccelerators(advertised, observed []Accelerator, tolerance float64) DeviceComparison

CompareAccelerators compares an observed per-device inventory (for example Outpost sysinfo GPUs mapped to Accelerator: model name plus per-device memory bytes) against advertised devices. Models compare case- and punctuation-insensitively; observed memory below advertised by more than tolerance (fraction, e.g. 0.05 for driver reserve) is a mismatch. Zero observed memory means unobserved and is not compared. Devices are compared one by one, never summed.

func (DeviceComparison) Match

func (c DeviceComparison) Match() bool

Match reports no observed-versus-advertised difference.

type DeviceMismatch

type DeviceMismatch struct {
	Kind            MismatchKind `json:"kind"`
	Index           int          `json:"index"`
	AdvertisedModel string       `json:"advertised_model,omitempty"`
	ObservedModel   string       `json:"observed_model,omitempty"`
	AdvertisedBytes int64        `json:"advertised_bytes,omitempty"`
	ObservedBytes   int64        `json:"observed_bytes,omitempty"`
}

DeviceMismatch is one difference. Index is the position in the paired (model, memory-descending) ordering; it is -1 for a count mismatch.

type Dispatcher

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

Dispatcher runs lifecycle operations for one provider through its adapter and the journal.

func Open

func Open(ctx context.Context, m Manifest, opts Options) (*Dispatcher, error)

Open resolves the credential, builds the adapter for m's form and returns the dispatcher. It makes no provider call. An executable manifest under ExecDisabled is refused with ErrExecDisabled before any process starts.

func (*Dispatcher) Adapter

func (d *Dispatcher) Adapter() Adapter

Adapter returns the underlying adapter (guarded). Callers that need a raw read (inspect/list without the dispatcher) may use it.

func (*Dispatcher) CompleteWork

func (d *Dispatcher) CompleteWork(ctx context.Context, workRef string) ([]Result, error)

CompleteWork destroys every journaled work-bound temporary resource created for workRef, with no confirmation input.

func (*Dispatcher) Do

func (d *Dispatcher) Do(ctx context.Context, req Request) (Result, error)

Do runs one operation. Read operations (validate, capacity, plan, inspect, list) go to the adapter under the common timeout and retries and are not journaled. A mutating operation is journaled before and after the call; a replay of a completed key answers from the journal without a provider call — except a create, whose resource is proven to still exist first (createReplay); a pending key is reconciled first; and a destroy is authorized per A6 before anything reaches the adapter.

func (*Dispatcher) ExpireTemporary

func (d *Dispatcher) ExpireTemporary(ctx context.Context) ([]Result, error)

ExpireTemporary destroys every journaled resource whose TTL authorization has expired by the dispatcher's clock, with no confirmation input: the authorization was given at create. Each resource is destroyed exactly once (TemporaryKey). Failures are reported per resource and leave it journaled active with its cost.

func (*Dispatcher) Manifest

func (d *Dispatcher) Manifest() Manifest

Manifest returns the provider's manifest.

func (*Dispatcher) Redact

func (d *Dispatcher) Redact(s string) string

Redact scrubs s: the credential literal(s), then the caller's Redactor.

func (*Dispatcher) Resume

func (d *Dispatcher) Resume(ctx context.Context) (ResumeReport, error)

Resume reconciles every pending operation in the journal — a create whose result was never recorded, an ambiguous destroy — from the provider, before anything is retried. It never creates or destroys: it only asks and records. Call it once at process start.

func (*Dispatcher) View

func (d *Dispatcher) View(ctx context.Context) (JournalView, error)

View loads and folds the provider's journal.

type EndpointReserver

type EndpointReserver interface {
	ReserveEndpoint(ctx context.Context, spec Spec) (Reservation, error)
}

EndpointReserver is the optional capability of reserving a host's stable public address before the host is created. An adapter that implements it is asked once, ahead of enrollment.

type Error

type Error struct {
	Code      ErrorCode `json:"code"`
	Message   string    `json:"message"`
	Retryable bool      `json:"retryable,omitempty"`
}

Error is a structured, normalized error.

func AuthorizeDestroy

func AuthorizeDestroy(req Request, res Resource) *Error

AuthorizeDestroy is the full A6 check against the resource as the provider reports it: the static check, and for a temporary authorization the resource must have been created as temporary (TagTemporary) and, when the authorization names a work ref, carry that work tag.

func CheckDestroyAuthorization

func CheckDestroyAuthorization(req Request) *Error

CheckDestroyAuthorization is the static half of A6, decidable before any provider call: a destroy must carry either a user confirmation bound to exactly this resource ID and this idempotency key, or a temporary authorization. A confirmation is single use by construction — it names one idempotency key, and a replay under that key is the same operation. A temporary authorization still has to match the resource's recorded tags; see AuthorizeDestroy.

func CheckRequest

func CheckRequest(m Manifest, req Request) *Error

CheckRequest validates req against manifest m without calling any provider: protocol version, a declared capability for req.Op (an undeclared op is unsupported_capability and is never substituted), an idempotency key on mutating ops, a resource ID where one is needed, and the static half of the destroy authorization (see CheckDestroyAuthorization).

func (*Error) Error

func (e *Error) Error() string

type ErrorCode

type ErrorCode string

ErrorCode is a normalized error code.

const (
	ErrUnsupportedCapability ErrorCode = "unsupported_capability"
	ErrConfirmationRequired  ErrorCode = "confirmation_required"
	ErrNotOwned              ErrorCode = "not_owned" // untagged or foreign resource
	ErrNotFound              ErrorCode = "not_found"
	ErrInvalidRequest        ErrorCode = "invalid_request"
	ErrBudgetExceeded        ErrorCode = "budget_exceeded"
	ErrQuotaExceeded         ErrorCode = "quota_exceeded"
	ErrInvalidCredentials    ErrorCode = "invalid_credentials"
	ErrProtocolMismatch      ErrorCode = "protocol_mismatch"
	ErrRateLimited           ErrorCode = "rate_limited"
	ErrTimeout               ErrorCode = "timeout"
	ErrProvider              ErrorCode = "provider_error"
	ErrNeedsManualReconcile  ErrorCode = "needs_manual_reconcile"
	ErrExecDisabled          ErrorCode = "exec_disabled" // executable plugin in a no-exec context
)

type ExecOptions

type ExecOptions struct {
	// Stderr receives the plugin's diagnostics; nil discards them.
	Stderr io.Writer
	// Env is the plugin's environment; nil inherits the caller's.
	Env []string
	// Dir is the plugin's working directory; empty inherits the caller's.
	Dir string
}

ExecOptions configures the executable-plugin runner.

type ExecPolicy

type ExecPolicy int

ExecPolicy says whether executable plugins may run in this process.

const (
	// ExecDisabled refuses every executable plugin (the master).
	ExecDisabled ExecPolicy = iota
	// ExecAllowed runs executable plugins (user-owned compute only).
	ExecAllowed
)

type FileJournal

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

FileJournal is the local JournalStore: one JSON-lines file per provider under dir, appended with O_APPEND so concurrent writers on one host interleave whole records. Files are 0600, the directory 0700.

func NewFileJournal

func NewFileJournal(dir string) (*FileJournal, error)

NewFileJournal returns a file store rooted at dir, creating it.

func (*FileJournal) Append

func (f *FileJournal) Append(_ context.Context, e JournalEntry) error

Append implements JournalStore.

func (*FileJournal) Dir

func (f *FileJournal) Dir() string

Dir is the store's directory.

func (*FileJournal) Load

func (f *FileJournal) Load(_ context.Context, provider string) ([]JournalEntry, error)

Load implements JournalStore. A truncated last line (a crash mid-write) is ignored; any other malformed line is an error.

type Form

type Form string

Form is the shape of a provider package.

const (
	FormDeclarative Form = "declarative"
	FormExecutable  Form = "executable"
	// FormBuiltin is a Go adapter linked into the host (e.g. the
	// DigitalOcean reference adapter). It has neither Argv nor Declarative.
	FormBuiltin Form = "builtin"
)

type JournalEntry

type JournalEntry struct {
	Seq            int64          `json:"seq,omitempty"`
	At             time.Time      `json:"at"`
	Provider       string         `json:"provider"`
	Form           Form           `json:"form,omitempty"`
	Op             Op             `json:"op"`
	IdempotencyKey string         `json:"idempotency_key,omitempty"`
	Phase          Phase          `json:"phase"`
	Attempt        int            `json:"attempt,omitempty"`
	ResourceID     string         `json:"resource_id,omitempty"`        // before the call
	ResultID       string         `json:"result_resource_id,omitempty"` // after the call
	State          State          `json:"state,omitempty"`
	Tags           []string       `json:"tags,omitempty"`
	Spec           *Spec          `json:"spec,omitempty"`
	Authorization  *Authorization `json:"authorization,omitempty"`
	Error          *Error         `json:"error,omitempty"`
	Cost           *CostReport    `json:"cost,omitempty"`
	Note           string         `json:"note,omitempty"`
}

JournalEntry is one journal record.

type JournalStore

type JournalStore interface {
	Append(ctx context.Context, e JournalEntry) error
	Load(ctx context.Context, provider string) ([]JournalEntry, error)
}

JournalStore persists journal records for one host. Append must be durable before it returns; Load returns every record of provider in append order. Implementations must be safe for concurrent use.

type JournalView

type JournalView struct {
	Operations []Operation
	Resources  []JournaledResource
}

JournalView folds a provider's records into operations and resources.

func Replay

func Replay(entries []JournalEntry) JournalView

Replay folds entries (append order) into a view. It is deterministic and pure: the same records always give the same view.

func (JournalView) Find

func (v JournalView) Find(op Op, key string) (Operation, bool)

Find returns the operation for (op, key).

func (JournalView) ManualReconcile

func (v JournalView) ManualReconcile() []Operation

ManualReconcile returns the operations a human has to look at.

func (JournalView) Pending

func (v JournalView) Pending() []Operation

Pending returns the operations whose outcome is unknown.

func (JournalView) Resource

func (v JournalView) Resource(id string) (JournaledResource, bool)

Resource returns the journaled resource with id.

type JournaledResource

type JournaledResource struct {
	ID        string
	CreateKey string
	Tags      []string
	State     State
	// Temporary is the temporary-lifecycle authorization recorded at
	// create, if any.
	Temporary *Authorization
	// Destroyed is true once a destroy result or reconciliation reported
	// StateDeleted. A refused or failed destroy leaves it false.
	Destroyed bool
	// Cost is the latest cost report (stop, refused destroy, destroy).
	Cost *CostReport
	Last time.Time
}

JournaledResource is the journal's view of one provider resource.

type Lifecycle

type Lifecycle struct {
	StopKeepsBilling bool   `json:"stop_keeps_billing"`
	StopKeepsDisk    bool   `json:"stop_keeps_disk"`
	ReleaseDeletes   bool   `json:"release_deletes"`
	Note             string `json:"note,omitempty"`
}

Lifecycle states what stop and release mean for cost and data.

type LifecycleMode

type LifecycleMode string
const (
	LifecyclePersistent LifecycleMode = "persistent"
	LifecycleEphemeral  LifecycleMode = "ephemeral"
)

type Manifest

type Manifest struct {
	Name            string       `json:"name" yaml:"name"`
	Kind            string       `json:"kind" yaml:"kind"` // KindInfra ("infra")
	Form            Form         `json:"form" yaml:"form"`
	Version         string       `json:"version,omitempty" yaml:"version,omitempty"`
	ProtocolVersion string       `json:"protocol_version" yaml:"protocol_version"`
	Summary         string       `json:"summary,omitempty" yaml:"summary,omitempty"`
	Capabilities    []Capability `json:"capabilities" yaml:"capabilities"`
	// Argv is the executable plugin's command line (FormExecutable only).
	// It is exec'd directly, never through a shell.
	Argv []string `json:"argv,omitempty" yaml:"argv,omitempty"`
	// Declarative holds the endpoint/template/lifecycle-mapping document
	// (FormDeclarative only). Its schema is owned by the declarative engine.
	Declarative json.RawMessage `json:"declarative,omitempty" yaml:"-"`
}

Manifest identifies a provider package. Credentials are never manifest fields; they are references resolved by the caller.

func (Manifest) Supports

func (m Manifest) Supports(op Op) bool

Supports reports whether the manifest declares op as a capability.

type MemoryJournal

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

MemoryJournal is an in-memory JournalStore (tests, the master's cache).

func NewMemoryJournal

func NewMemoryJournal() *MemoryJournal

NewMemoryJournal returns an empty in-memory store.

func (*MemoryJournal) Append

Append implements JournalStore.

func (*MemoryJournal) Load

func (m *MemoryJournal) Load(_ context.Context, provider string) ([]JournalEntry, error)

Load implements JournalStore.

type MismatchKind

type MismatchKind string

MismatchKind classifies an observed-versus-advertised accelerator difference.

const (
	MismatchCount  MismatchKind = "count"
	MismatchModel  MismatchKind = "model"
	MismatchMemory MismatchKind = "memory"
)

type ModelSpec

type ModelSpec struct {
	Digest          string `json:"digest,omitempty"`
	Quantization    string `json:"quantization,omitempty"`
	ContextLength   int    `json:"context_length,omitempty"`
	Params          int64  `json:"params,omitempty"`
	WeightBytes     int64  `json:"weight_bytes,omitempty"`
	KVBytesPerToken int64  `json:"kv_bytes_per_token,omitempty"`
}

ModelSpec carries the registry fields (Digest, Quantization, ContextLength) plus the weight/KV metadata the estimate needs. Zero means unknown.

type Network

type Network struct {
	Known         bool  `json:"known"`
	BandwidthMbps int64 `json:"bandwidth_mbps,omitempty"`
	TransferBytes int64 `json:"transfer_bytes,omitempty"` // monthly allowance
}

Network holds network characteristics; Known is false when the provider does not say.

type Offer

type Offer struct {
	Account       string        `json:"account,omitempty"`
	Region        string        `json:"region"`
	SKU           string        `json:"sku"`
	Purchase      PurchaseMode  `json:"purchase"`
	CPU           CPU           `json:"cpu"`
	MemoryBytes   int64         `json:"memory_bytes"`
	Accelerators  []Accelerator `json:"accelerators,omitempty"`
	Storage       []Storage     `json:"storage,omitempty"`
	Network       Network       `json:"network"`
	Price         Price         `json:"price"`
	Availability  Availability  `json:"availability"`
	Quota         Quota         `json:"quota"`
	Allocation    *Allocation   `json:"allocation,omitempty"`
	Lifecycle     Lifecycle     `json:"lifecycle"`
	Qualification Qualification `json:"qualification"`
}

Offer is one normalized purchasable shape: advertised catalog data plus optional account quota and observed allocation.

func DiscoverOffers

func DiscoverOffers(ctx context.Context, a Adapter) ([]Offer, error)

DiscoverOffers runs OpCapacity on a and returns its normalized offers. An adapter that does not emit offers yields none.

func (Offer) CompareObserved

func (o Offer) CompareObserved() DeviceComparison

CompareObserved compares the offer's advertised accelerators with its observed Allocation. A nil allocation means no observation was made.

func (Offer) FitsSingleDevice

func (o Offer) FitsSingleDevice(need int64) bool

FitsSingleDevice reports whether need bytes fit on one device.

func (Offer) PerDeviceMemoryBytes

func (o Offer) PerDeviceMemoryBytes() []int64

PerDeviceMemoryBytes returns each accelerator's own memory, in order.

func (Offer) Placeable

func (o Offer) Placeable() (bool, string)

Placeable reports whether the offer can be bought now under v1 policy and why not. Unknown availability or quota does not block; it is surfaced by the caller from the Unknown states.

func (Offer) SingleDeviceFitBytes

func (o Offer) SingleDeviceFitBytes() int64

SingleDeviceFitBytes is the largest model/working set one device can hold: the per-device maximum, never a sum across devices.

type OffersData

type OffersData struct {
	Offers []Offer `json:"offers"`
}

OffersData is the "offers" payload of an OpCapacity result's Data.

type Op

type Op string

Op is one lifecycle operation.

const (
	OpValidate Op = "validate" // validate credentials
	OpCapacity Op = "capacity" // discover regions/sizes
	OpPlan     Op = "plan"
	OpCreate   Op = "create"
	OpInspect  Op = "inspect"
	OpList     Op = "list"
	OpStart    Op = "start"
	OpStop     Op = "stop"
	OpDestroy  Op = "destroy"
	// Optional capabilities.
	OpReboot Op = "reboot"
	OpResize Op = "resize"
)

func Ops

func Ops() []Op

Ops returns every operation of protocol v1.

func (Op) Known

func (op Op) Known() bool

Known reports whether op is an operation of protocol v1.

func (Op) Mutating

func (op Op) Mutating() bool

Mutating reports whether op changes provider state and therefore needs an idempotency key.

type Operation

type Operation struct {
	Op             Op
	IdempotencyKey string
	ResourceID     string // the resource the op addressed or produced
	Attempts       int
	// Pending is true when the latest record is an intent or an ambiguous
	// result: the provider may have acted and nothing proves it either way.
	Pending bool
	// Done is true when a successful result or a reconciled outcome closed
	// the op. Result is that record.
	Done   bool
	Result *JournalEntry
	// NeedsManualReconcile is true when reconciliation could not prove
	// the outcome; a human has to look at the provider.
	NeedsManualReconcile bool
	// Retired is true when the resource a completed operation produced is
	// gone, so Result no longer describes anything: the key may act
	// again. A new attempt (an intent record) clears it.
	Retired bool
	// Refused counts refusals before any provider call.
	Refused int
	First   time.Time
	Last    time.Time
}

Operation is the journal's view of one (op, idempotency key) pair: the records that describe it, folded into its current standing.

type Options

type Options struct {
	// Owner scopes ownership tags (ValidOwner). Required.
	Owner string
	// Exec is the executable-plugin policy; the zero value is disabled.
	Exec ExecPolicy
	// Journal is the durable store; nil opens the file store under
	// DefaultJournalDir (BASHY_HOME/provider/journal).
	Journal JournalStore
	// Timeout bounds each provider call (default 60s).
	Timeout time.Duration
	// MutatingTimeout bounds a mutating call (create, destroy, power,
	// resize) when it is larger than Timeout; zero means Timeout.
	//
	// It exists because those two budgets are not the same size. A read
	// answers in a second or it is broken, but an adapter that brings a
	// host all the way to its serving shape before answering — AWS
	// Lightsail waits for "running" and then applies the firewall and
	// the static IP — legitimately runs for minutes. Bounding it at the
	// read timeout cancels the adapter mid-sequence and the dispatcher
	// then reconciles the create as "the resource exists", reporting
	// success for a host whose remaining steps never ran.
	MutatingTimeout time.Duration
	// Retries is how many more attempts a retryable failure gets after
	// the first (default 0: one attempt). A create is never retried
	// before its outcome has been reconciled by idempotency tag.
	Retries int
	// Backoff is the wait before a retry, multiplied by the attempt
	// number (default 0).
	Backoff time.Duration
	// Now is the clock (TTL expiry); nil means time.Now.
	Now func() time.Time
	// Redact is applied to every journaled and logged string after the
	// credential literal has been scrubbed.
	Redact Redactor
	// Credentials resolves the credential at Open. Required for the
	// built-in and declarative forms.
	Credentials CredentialSource
	// Builtins maps a built-in manifest name to its factory.
	Builtins map[string]BuiltinFactory
	// HTTPClient is used by the declarative engine (default 60s client).
	HTTPClient *http.Client
	// ExecStderr, ExecEnv and ExecDir configure the executable runner.
	// The dispatcher never puts the credential in ExecEnv.
	ExecStderr io.Writer
	ExecEnv    []string
	ExecDir    string
	// ExecFactory builds the executable runner (default NewExecAdapter).
	// Tests install a hook that fails when called.
	ExecFactory func(m Manifest, opts ExecOptions) (Adapter, error)
	// Log receives one redacted line per noteworthy event; nil is silent.
	Log func(line string)
}

Options configures a Dispatcher.

type Phase

type Phase string

Phase is the stage a journal record describes.

const (
	// PhaseIntent is written before the provider call.
	PhaseIntent Phase = "intent"
	// PhaseResult is written after the provider answered (success or a
	// normalized failure that proves nothing happened).
	PhaseResult Phase = "result"
	// PhaseRefused is a request the dispatcher refused before any
	// provider call (no confirmation, exec disabled, unsupported op).
	PhaseRefused Phase = "refused"
	// PhaseAmbiguous is a call whose outcome is unknown (timeout, lost
	// response, 5xx): the provider may or may not have acted.
	PhaseAmbiguous Phase = "ambiguous"
	// PhaseReconciled closes an intent or ambiguous record from what the
	// provider reports (list by idempotency tag, inspect by ID).
	PhaseReconciled Phase = "reconciled"
	// PhaseNeedsManualReconcile closes nothing: the outcome could not be
	// proven and a human has to look.
	PhaseNeedsManualReconcile Phase = "needs_manual_reconcile"
	// PhaseRetired says a completed operation no longer answers its key:
	// the resource it produced is gone (destroyed here, swept, or deleted
	// in the provider's own console), so replaying its result would
	// report a resource that does not exist. It closes nothing and
	// rewrites nothing — the record is the fact that the old answer is
	// dead, and the key is free to act again.
	PhaseRetired Phase = "retired"
)

type Placement

type Placement string
const (
	PlacementGPU         Placement = "gpu"
	PlacementUnified     Placement = "unified_memory"
	PlacementCPUFallback Placement = "cpu_fallback"
)

type Plan

type Plan struct {
	Offer          Offer         `json:"offer"`
	Fits           bool          `json:"fits"`
	Reason         string        `json:"reason,omitempty"`
	Placement      Placement     `json:"placement,omitempty"`
	NeedBytes      int64         `json:"need_bytes,omitempty"`
	Uncertain      []string      `json:"uncertain,omitempty"`
	Cost           CostPlan      `json:"cost"`
	LifecycleMode  LifecycleMode `json:"lifecycle_mode"`
	Purchase       PurchaseMode  `json:"purchase"`
	MaxLifetime    time.Duration `json:"max_lifetime,omitempty"`
	CleanupTrigger string        `json:"cleanup_trigger,omitempty"`
	Notes          []string      `json:"notes,omitempty"`
}

Plan explains one offer's fit and cost.

func PlanFit

func PlanFit(o Offer, w Workload) Plan

PlanFit judges whether w fits o and projects cost and lifecycle.

type Price

type Price struct {
	Known       bool      `json:"known"`
	USDPerHour  float64   `json:"usd_per_hour,omitempty"`
	USDPerMonth float64   `json:"usd_per_month,omitempty"`
	ObservedAt  time.Time `json:"observed_at,omitempty"`
}

Price is a unit price that may be unknown.

type PurchaseMode

type PurchaseMode string

PurchaseMode is how an offer is bought.

const (
	PurchaseOnDemand PurchaseMode = "on_demand"
	PurchaseSpot     PurchaseMode = "spot"
)

type Qualification

type Qualification struct {
	Qualified bool   `json:"qualified"`
	Reason    string `json:"reason,omitempty"`
}

Qualification says whether the offer is usable under v1 policy.

type Quota

type Quota struct {
	Known      bool      `json:"known"`
	Limit      int       `json:"limit,omitempty"`
	Used       int       `json:"used,omitempty"`
	ObservedAt time.Time `json:"observed_at,omitempty"`
}

Quota is account-level headroom for the offer's resource class; it is distinct from the advertised catalog. Known is false when not observed.

func (Quota) Exhausted

func (q Quota) Exhausted() bool

Exhausted reports a known quota with no headroom.

type Redactor

type Redactor func(string) string

Redactor scrubs a string before it is journaled or logged. The caller wires pkg/redact's Scrubber.String here; the dispatcher always scrubs the credential literal itself, with or without a Redactor.

type Request

type Request struct {
	ProtocolVersion string         `json:"protocol_version"`
	Op              Op             `json:"op"`
	IdempotencyKey  string         `json:"idempotency_key,omitempty"` // required for mutating ops
	ResourceID      string         `json:"resource_id,omitempty"`
	Spec            *Spec          `json:"spec,omitempty"`
	Authorization   *Authorization `json:"authorization,omitempty"`
}

Request is one operation call.

type Reservation

type Reservation struct {
	// Name is the provider's own name for the reservation (e.g. a
	// Lightsail static IP name), so a later destroy can find it.
	Name string `json:"name,omitempty"`
	// Address is the reserved IP.
	Address string `json:"address,omitempty"`
	// Endpoint is the public endpoint hint that address answers on, or
	// "" when the provider has no hint to offer for it.
	Endpoint string `json:"endpoint,omitempty"`
	// Reused is true when the reservation already existed and was taken
	// over rather than allocated. A replayed provision must not allocate
	// a second address.
	Reused bool `json:"reused,omitempty"`
}

Reservation is a stable public address held for a host that does not exist yet. The zero value means nothing was reserved.

func ReserveEndpoint

func ReserveEndpoint(ctx context.Context, a Adapter, spec Spec) (Reservation, error)

ReserveEndpoint reserves a stable address for spec through a, or returns the zero Reservation when a reserves nothing — an adapter without the capability is not an error, it just has no hint.

func (Reservation) Held

func (r Reservation) Held() bool

Held reports whether r holds an address.

type Resource

type Resource struct {
	ID        string    `json:"id"` // provider resource ID, preserved verbatim
	Name      string    `json:"name,omitempty"`
	State     State     `json:"state"`
	RawStatus string    `json:"raw_status,omitempty"`
	Region    string    `json:"region,omitempty"`
	Size      string    `json:"size,omitempty"`
	Tags      []string  `json:"tags,omitempty"`
	PublicIPs []string  `json:"public_ips,omitempty"`
	CreatedAt time.Time `json:"created_at,omitempty"`
}

Resource is a provider resource as reported by the provider.

type Result

type Result struct {
	ProtocolVersion string          `json:"protocol_version"`
	Op              Op              `json:"op"`
	Resource        *Resource       `json:"resource,omitempty"`
	Resources       []Resource      `json:"resources,omitempty"`
	Cost            *CostReport     `json:"cost,omitempty"`
	Data            json.RawMessage `json:"data,omitempty"` // validate/capacity/plan payloads
	Error           *Error          `json:"error,omitempty"`
}

Result is one operation's outcome. Exactly one of the payload fields or Error is meaningful.

func Failure

func Failure(op Op, code ErrorCode, format string, args ...any) (Result, error)

Failure builds the (Result, error) pair for a normalized failure.

func (Result) Err

func (r Result) Err() error

Err returns r.Error as an error, or nil.

type ResumeReport

type ResumeReport struct {
	Pending              int // operations found pending
	Reconciled           int // proven done, result journaled
	NotApplied           int // proven not done; a replay may retry
	NeedsManualReconcile int
}

ResumeReport summarizes Resume.

type Spec

type Spec struct {
	Name   string   `json:"name,omitempty"`
	Region string   `json:"region,omitempty"`
	Size   string   `json:"size,omitempty"`
	Image  string   `json:"image,omitempty"`
	Tags   []string `json:"tags,omitempty"`
	// SSHKeys are provider key IDs or fingerprints installed at first boot.
	SSHKeys []string          `json:"ssh_keys,omitempty"`
	Labels  map[string]string `json:"labels,omitempty"`
	// UserData is opaque (e.g. an enrollment bundle) and passed through unread.
	UserData []byte `json:"user_data,omitempty"`
}

Spec is the create/plan input.

type State

type State string

State is the normalized lifecycle state of a provider resource. It says nothing about satellite installation or readiness.

const (
	StatePending  State = "pending"
	StateRunning  State = "running"
	StateStopped  State = "stopped"
	StateDeleting State = "deleting"
	StateDeleted  State = "deleted"
	StateError    State = "error"
	StateUnknown  State = "unknown"
)

type StaticCredential

type StaticCredential string

StaticCredential is a CredentialSource holding one value in memory (a use-once token the caller already resolved).

func (StaticCredential) Credential

func (s StaticCredential) Credential(context.Context, string) (string, error)

Credential implements CredentialSource.

type Storage

type Storage struct {
	Kind       string `json:"kind,omitempty"` // "boot", "volume", ...
	SizeBytes  int64  `json:"size_bytes"`
	Persistent bool   `json:"persistent"`
	Attachable bool   `json:"attachable"`
}

Storage is one storage component of an offer.

type Workload

type Workload struct {
	Model          ModelSpec
	Context        int
	Concurrency    int
	AllowCPU       bool
	AllowSpot      bool
	Lifecycle      LifecycleMode
	MaxLifetime    time.Duration // ignored for persistent
	CleanupTrigger string
	Hours          float64 // expected run time for the quote
}

Workload is what the worker must run.

Directories

Path Synopsis
aws
Package aws is the AWS Lightsail provider adapter (S522.2): a FormBuiltin provider.Adapter over the Lightsail JSON API, reached through `bashy infra provision aws` (or `--provider aws`).
Package aws is the AWS Lightsail provider adapter (S522.2): a FormBuiltin provider.Adapter over the Lightsail JSON API, reached through `bashy infra provision aws` (or `--provider aws`).
fakeec2
Package fakeec2 is a deterministic in-process stand-in for the AWS EC2 query API, the Service Quotas JSON API and the S3 object API, for testing the EC2 GPU worker adapter (pkg/provider/aws NewEC2).
Package fakeec2 is a deterministic in-process stand-in for the AWS EC2 query API, the Service Quotas JSON API and the S3 object API, for testing the EC2 GPU worker adapter (pkg/provider/aws NewEC2).
fakelightsail
Package fakelightsail is a deterministic in-process stand-in for the AWS Lightsail and Cost Explorer JSON APIs, for testing pkg/provider/aws.
Package fakelightsail is a deterministic in-process stand-in for the AWS Lightsail and Cost Explorer JSON APIs, for testing pkg/provider/aws.
Package conformance is the reusable provider conformance suite (S472.14): one func over states and transitions, idempotency and reconciliation, normalized errors, unsupported operations, stop-versus-destroy billing and data semantics, and A6 destroy confirmation.
Package conformance is the reusable provider conformance suite (S472.14): one func over states and transitions, idempotency and reconciliation, normalized errors, unsupported operations, stop-versus-destroy billing and data semantics, and A6 destroy confirmation.
Package digitalocean is the reference provider adapter (S472.4a): a FormBuiltin provider.Adapter over the DigitalOcean v2 API.
Package digitalocean is the reference provider adapter (S472.4a): a FormBuiltin provider.Adapter over the DigitalOcean v2 API.
fakedo
Package fakedo is an in-process fake of the DigitalOcean v2 API subset the provider adapter uses, for tests only (httptest; it never reaches the network).
Package fakedo is an in-process fake of the DigitalOcean v2 API subset the provider adapter uses, for tests only (httptest; it never reaches the network).
Package enroll is the OSS client for the public dhnt.io satellite enrollment API (S472.13b item 1, executable path).
Package enroll is the OSS client for the public dhnt.io satellite enrollment API (S472.13b item 1, executable path).

Jump to

Keyboard shortcuts

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