Documentation
¶
Overview ¶
Package node pairs this machine with a Cinchapi account, keeps the link to the account open while paired, and serves HTTPS with API keys on a server with a public name.
Index ¶
- Constants
- Variables
- func CertManager(h config.HTTPSConfig, dir string) *autocert.Manager
- func CmdHTTPS(p config.Paths, args []string) error
- func CmdKey(p config.Paths, args []string) error
- func CmdPair(p config.Paths, args []string) error
- func CmdUnpair(p config.Paths) error
- func HTTPSTLS(h config.HTTPSConfig, dir string) *tls.Config
- func OfferPairing(p config.Paths) error
- func PrintHTTPS(p config.Paths)
- func PrintLink(p config.Paths)
- func RequireKey(keysPath string, next http.Handler) http.Handler
- func SaveNode(path string, n Node) error
- func ServeHTTPS(ctx context.Context, p config.Paths, h config.HTTPSConfig, ...)
- func ValidKey(path, key string) (bool, error)
- func WatchChanges(ctx context.Context, every time.Duration, changes chan<- struct{})
- type APIKey
- type Link
- type LinkOptions
- type LinkState
- type Node
- type PairingRequest
Constants ¶
const ( // CloseRefused means the account does not accept this node's key: the // key is unknown or revoked, or the node was deleted. CloseRefused websocket.StatusCode = 4401 // CloseReplaced means a newer link opened with the same key, such as // from a second machine that holds a copy of the node file. CloseReplaced websocket.StatusCode = 4409 )
The close codes the gateway sends, besides the standard ones.
const ( LinkUnpaired = "unpaired" LinkConnected = "connected" LinkRefused = "refused" LinkReplaced = "replaced" )
The states a link reports in LinkState.State.
const ( // LinkReadLimit is the largest frame the link reads. A request can // carry images, and base64 makes it a third larger. LinkReadLimit = 64 << 20 )
Variables ¶
var ( Replies = bufio.NewReader(os.Stdin) Askable = stdinIsTerminal )
Replies reads the answers to pasture's questions, and Askable reports whether a person can give them. Tests replace both.
var ( // ErrPairingExpired marks a code that expired before anyone approved // it. ErrPairingExpired = errors.New("the pairing code expired before " + "anyone approved it. Run pasture pair again") )
var OpenBrowser = func(url string) bool { var cmd *exec.Cmd _, xdgErr := exec.LookPath("xdg-open") display := os.Getenv("DISPLAY") != "" || os.Getenv("WAYLAND_DISPLAY") != "" if runtime.GOOS == "darwin" { cmd = exec.Command("open", url) } else if runtime.GOOS == "linux" && display && xdgErr == nil { cmd = exec.Command("xdg-open", url) } if cmd == nil || cmd.Start() != nil { return false } else { go cmd.Wait() return true } }
OpenBrowser opens url in your browser, without waiting for the browser, and reports whether it could start one: `open` on macOS, and `xdg-open` on Linux when the session has a display. Tests replace it.
var PairingSecond = time.Second
PairingSecond is the unit of the waits that the account server sets during pairing: the time between polls, and how long the code works. Tests shorten it.
Functions ¶
func CertManager ¶
func CertManager(h config.HTTPSConfig, dir string) *autocert.Manager
CertManager returns the manager that gets and renews the certificate for the public name from Let's Encrypt. It asks for that name alone, so a request under another name cannot make it ask for more. It compares names as plain text, as HTTPSTLS does. It keeps the certificates and the account key in dir. It accepts Let's Encrypt's subscriber agreement, which turning on HTTPS agrees to.
func CmdHTTPS ¶
CmdHTTPS sets the public name that `pasture serve` serves HTTPS for, or turns HTTPS off with "off". The change applies when pasture starts.
func CmdPair ¶
CmdPair pairs this machine with your Cinchapi account, so Cinchapi can use its models. It takes an optional --name for the machine, which defaults to the machine's own name.
func CmdUnpair ¶
CmdUnpair removes this machine's pairing. Your account keeps the node, offline, until you delete it there, which also revokes its key.
func HTTPSTLS ¶
func HTTPSTLS(h config.HTTPSConfig, dir string) *tls.Config
HTTPSTLS returns the TLS config of the HTTPS listener: autocert's, behind a check that the name a client asks for is the public name. autocert passes that name through idna and Unicode normalization before its own checks. That code has had bugs a crafted name could reach, such as an endless loop (GO-2026-5970, fixed in x/text v0.39.0), so only the public name, which CmdHTTPS checked, reaches autocert.
func OfferPairing ¶
OfferPairing ends `pasture install`. On a machine that is not paired, it asks whether to pair, and pairs on yes or a bare Enter. With no person to ask, it says how to pair later. A pairing that does not finish is not an error, because pasture itself is installed and runs.
func PrintHTTPS ¶
PrintHTTPS says where pasture serves HTTPS, when it does, for `pasture status`.
func PrintLink ¶
PrintLink says how this machine's link to the Cinchapi account stands, for `pasture status`.
func RequireKey ¶
RequireKey guards the HTTPS listener. It answers 401 to a request without a valid API key in its Authorization header, and 403 to one outside remoteRoutes. It passes the rest to next as the node link does: marked by trust, with Host set to localhost, and without the Origin and Authorization headers, because Ollama would refuse the public name and needs no key. It reads the keys file for each request, so a deleted key stops working at once.
func SaveNode ¶
SaveNode writes the node file at path in one step, readable and writable only by you.
func ServeHTTPS ¶
ServeHTTPS serves remoteRoutes over HTTPS for the config's public name until ctx ends. Each request needs an API key that `pasture key create` made. The certificate comes from Let's Encrypt, which checks the name on port 443, and autocert renews it. A listener that cannot start is logged and leaves the rest of pasture running.
func ValidKey ¶
ValidKey reports whether key matches a key in the keys file. It compares hashes in constant time, so the time an answer takes says nothing about the keys.
func WatchChanges ¶
WatchChanges sends on changes when the machine wakes from sleep or its network addresses change, checking every interval, until ctx ends. It notices sleep because the wall clock moves on during sleep while Go's monotonic clock does not, on macOS and Linux. A send never blocks; one waiting value is enough.
Types ¶
type APIKey ¶
type APIKey struct {
Name string `json:"name"`
Hash string `json:"hash"`
Created time.Time `json:"created"`
}
APIKey is one key that `pasture key create` made. pasture keeps only the key's SHA-256 hash, so the keys file does not hold the key itself.
type Link ¶
type Link struct {
Options LinkOptions
// contains filtered or unexported fields
}
Link keeps this machine's link to the Cinchapi gateway open while the machine is paired, so Cinchapi can use its models from anywhere. The machine connects out, so it works behind a home router. The link serves each request the gateway sends through pasture's own handler, so a moved-away model comes back first, and it serves only remoteRoutes.
func NewLink ¶
func NewLink(o LinkOptions) *Link
NewLink returns a Link that does nothing until Run.
func (*Link) Reload ¶
func (l *Link) Reload()
Reload makes the link read the node file again, without waiting: it connects after a pairing, and closes after an unpairing. A link that is waiting to connect again connects at once.
func (*Link) Run ¶
Run keeps the link open while the machine is paired, and serves each request from the gateway through handler. After a failure it waits 1 to 60 seconds, longer after each failure in a row, with jitter. It connects at once after a link that worked closes, after Reload, and after a value on Changes. Every failure stays inside Run, which returns only when ctx ends.
func (*Link) ServeHTTP ¶
func (l *Link) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP answers /pasture/link. A GET answers `pasture status` with the link's state. A POST has the link read the node file again, after `pasture pair` or `pasture unpair` changed it, and answers with the link's state; the link connects or closes after the answer.
type LinkOptions ¶
type LinkOptions struct {
// NodePath is the node file that pairing writes.
NodePath string
// Models lists the models for the gateway.
Models func(context.Context) ([]library.ModelRow, error)
// Changes receives a value when the machine wakes from sleep or its
// network changes. The link then checks itself at once, and a link
// that is waiting to connect connects at once.
Changes <-chan struct{}
// Unit scales every wait the contract names in seconds: pings every 20
// units, silence for 60, and so on. It is one second unless a test
// shortens it.
Unit time.Duration
// Logf receives one line per change of state; it defaults to the
// standard logger.
Logf func(string, ...any)
}
LinkOptions configures a Link.
type LinkState ¶
type LinkState struct {
// State is "unpaired", "connecting", "connected", "waiting" (to
// connect again after a failure), "refused" (the account refused the
// key), or "replaced" (another link uses the key).
State string `json:"state"`
EndpointID string `json:"endpoint_id,omitempty"`
// Since is when the link entered this state.
Since time.Time `json:"since"`
// Error says why the link is not connected, when it is not.
Error string `json:"error,omitempty"`
// Retry is when the link tries to connect again.
Retry time.Time `json:"retry,omitzero"`
}
LinkState is what `pasture status` shows about the link.
type Node ¶
type Node struct {
EndpointID string `json:"endpointId"`
NodeKey string `json:"nodeKey"`
LinkURL string `json:"linkUrl"`
}
Node is what pairing gives this machine: the id of its endpoint in your Cinchapi account, the key that proves a link comes from it, and the address of the link. Anyone who holds the key can serve as this machine, so it lives in node.json, which only you can read, and pasture never prints it.
type PairingRequest ¶
type PairingRequest struct {
Name string `json:"name"`
OS string `json:"os"`
Arch string `json:"arch"`
PastureVersion string `json:"pastureVersion"`
}
PairingRequest tells the account server about this machine. The approval page shows it, so you can tell which machine asks to pair.