attached

package
v0.2.64 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MPL-2.0 Imports: 31 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package attached is a workspace held by a machine the fleet did not make: one that dialed in with `txco attach` and proved a key enrolled for that one workspace name.

(The name `attach` was taken twice over: the workspace verb that binds a terminal, and the package chassis/attach behind it.)

Index

Constants

View Source
const (
	PathCode   = "/v1/attach/code"   // POST {code}: what the code is for, without spending it
	PathEnroll = "/v1/attach/enroll" // POST, signed: spend the code, enroll the key
	PathLink   = "/v1/attach"        // GET, WebSocket: the link
)

The three routes a machine uses. All are public: a caller is either a machine with a code or a key, or nobody.

View Source
const (
	KindHello    = "hello"
	KindRequest  = "request"
	KindCancel   = "cancel"
	KindStop     = "stop"
	KindComplete = "complete"
	KindBye      = "bye"
)

Stream kinds.

View Source
const (
	ReasonReplaced = "replaced"
	ReasonRevoked  = "revoked"
	ReasonRefused  = "refused"
	ReasonShutdown = "shutdown"
)

Reasons a link is closed by the chassis. A machine told `replaced` or `revoked` stops serving that credential and does not reconnect.

View Source
const (
	DefaultCodeTTL = time.Hour
	MaxCodeTTL     = 24 * time.Hour
)

Code lifetimes: an hour unless asked, a day at most.

View Source
const (

	// DefaultLease is how long a claim stays live without a renewal. The
	// holder renews past half of it.
	DefaultLease = 10 * time.Minute
)

The claim says which connection holds a workspace NOW. It is liveness only. Whether a name is attached at all is the workspace's row in the runtime DB, never this: a missing or released claim reads "away", and nothing else.

THE INVARIANT: a connection with an older generation never becomes the holder, whatever the order of events.

Three things keep it:

  • A generation is issued once. It comes from a counter that never expires and is never reset.
  • Installing COMPARES generations. Compare-and-swap alone only proves that nothing changed since the read; it would let generation 10 write over 11 if 10 happened to read last. So an install refuses when the installed generation is its own or higher, and only then swaps.
  • The key never disappears. A release writes a marker that keeps the generation and has no expiry, so the highest generation ever installed is always there to compare with.
View Source
const ProtocolVersion = "txco-attach-v1"

ProtocolVersion is signed into every challenge, so an answer made for one version of this protocol is never an answer for another.

Variables

View Source
var (
	// ErrBadCode: no such code, or it is spent or expired. One answer for
	// all three: a caller learns nothing about which.
	ErrBadCode = errors.New("attached: the code is not valid")
	// ErrNameInUse: the provider holds a live workspace of this name.
	// Enrolling never destroys anything; the owner picks another name or
	// destroys that workspace first.
	ErrNameInUse = errors.New("attached: a workspace of that name already exists")
)
View Source
var ErrLinkDown = errors.New("attached: the link is down")

ErrLinkDown: there is no connection to send on right now.

View Source
var ErrReplaced = errors.New("attached: replaced by a newer connection")

ErrReplaced: a newer connection holds the name, or held it last. The connection that gets this closes as `replaced` and stops serving.

Functions

func AddressSuffix

func AddressSuffix(publicURL string) string

AddressSuffix is what an invite appends to a code: "@<host>" for an https address, "@<scheme>://<host>" for any other, and nothing for none.

func AsyncResultOf

func AsyncResultOf(raw json.RawMessage, lim workspace.Limits) (workspace.AsyncResult, error)

AsyncResultOf reads a completion's payload — a machine's word for how a detached job ended — into typed fields, cut to the chassis's own output caps. Nothing of the payload is kept as JSON: what a machine supplies is two strings, an exit code and a few flags.

func ChallengeBytes

func ChallengeBytes(host, credential, conn string, nonce []byte) []byte

ChallengeBytes is what a machine signs to prove it holds a credential's key ON THIS CONNECTION. Each part is length-prefixed, so no two different lists of parts make the same bytes.

The parts bind the answer to: this protocol; the host the machine dialed (an answer relayed from another host fails); the one credential; the one connection; and a nonce the chassis made for it and uses once.

func Dial

func Dial(ctx context.Context, hc *http.Client, base string) (net.Conn, string, error)

Dial opens the connection a Link runs on, and returns it with the host it was dialed by: the name the machine signs into its challenge answer.

func Final

func Final(err error) bool

Final reports whether err says this credential should not be tried again.

func Fingerprint

func Fingerprint(pub ed25519.PublicKey) string

Fingerprint is a key's id: SHA256:… over the SSH wire form, as ssh-keygen prints it. It is the keyid of the signed enrollment.

func RegisterRelay

func RegisterRelay(name string, c RelayConstructor)

RegisterRelay adds a named backend. Called from a backend package's init().

func SplitCode

func SplitCode(pasted string) (code, base string)

SplitCode separates what the owner pasted into the code and the address to dial. A bare host means https.

Types

type APIError

type APIError struct {
	Status  int
	Code    string
	Message string
}

APIError is a refusal from the chassis.

func (*APIError) Error

func (e *APIError) Error() string

type Answer

type Answer struct {
	Signature []byte `json:"signature"`
}

Answer is the machine's signature over ChallengeBytes.

type Challenge

type Challenge struct {
	Nonce []byte `json:"nonce"`
	Conn  string `json:"conn"`
	// Refused is set instead of a nonce when the hello itself is refused.
	Refused string `json:"refused,omitempty"`
}

Challenge is the chassis's answer to a hello.

type Claim

type Claim struct {
	// Gen is the generation of the connection that wrote this.
	Gen int64 `json:"gen"`
	// Released: no connection holds the name. Gen is still the highest
	// generation ever installed.
	Released bool `json:"released,omitempty"`

	Node       string    `json:"node,omitempty"`
	Conn       string    `json:"conn,omitempty"`
	LeaseUntil time.Time `json:"lease_until,omitzero"`

	// What the machine said of itself, for status. Never trusted for a
	// decision.
	Machine string    `json:"machine,omitempty"`
	Root    string    `json:"root,omitempty"`
	OS      string    `json:"os,omitempty"`
	Version string    `json:"version,omitempty"`
	Since   time.Time `json:"since,omitzero"`
}

Claim is the value at <tenant>/_txc.attach/<W>.

func (Claim) Holds

func (c Claim) Holds(conn string, gen int64) bool

Holds reports whether the claim is this connection's own, live or not.

func (Claim) Live

func (c Claim) Live(now time.Time) bool

Live reports whether the claim names a connection whose lease has not run out at now.

type Claims

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

Claims reads and writes claims in the KV.

func NewClaims

func NewClaims(k *kv.KV) *Claims

NewClaims returns the claims over k, with DefaultLease.

func (*Claims) Clear

func (c *Claims) Clear(ctx context.Context, tenant, w string) error

Clear marks W as held by no one, whoever holds it: the workspace was destroyed or its credential revoked. The marker keeps the highest generation installed, so a connection from before can never install after.

func (*Claims) Install

func (c *Claims) Install(ctx context.Context, tenant, w string, mine Claim) (written Claim, replaced *Claim, err error)

Install makes mine the holder of W, with a fresh lease. It returns the claim it wrote, and the claim it replaced when that one named a live connection (so the caller can tell that connection's node).

It refuses with ErrReplaced when the installed generation is mine's own or higher — including a released marker of that generation, so a connection that has released never comes back. The one exception is the same connection installing again over its own live claim, which only renews it.

func (*Claims) Lease

func (c *Claims) Lease() time.Duration

Lease is how long a written claim stays live.

func (*Claims) NextGen

func (c *Claims) NextGen(ctx context.Context, tenant, w string) (int64, error)

NextGen issues the next generation for W. Call it only after the connection has proved its key: the generation orders connections that are entitled to the name.

func (*Claims) Read

func (c *Claims) Read(ctx context.Context, tenant, w string) (claim Claim, found bool, err error)

Read returns W's claim. found is false when no connection ever installed one. A caller that needs the holder checks Live as well.

func (*Claims) Release

func (c *Claims) Release(ctx context.Context, tenant, w string, mine Claim) (released bool, err error)

Release marks W as held by no one, keeping mine's generation. It writes only over mine's own exact value, so an old connection's release never touches a newer claim. released is false when the claim was no longer mine: nothing was changed, and nothing needed to be.

func (*Claims) Renew

func (c *Claims) Renew(ctx context.Context, tenant, w string, mine Claim) (Claim, error)

Renew extends mine's lease. mine must be the exact claim this connection last wrote: the swap is from that value, so any other write since — a newer connection, a release, a destroy — fails it with ErrReplaced.

type CodeInfo

type CodeInfo struct {
	Label     string
	ExpiresAt time.Time
}

CodeInfo is what a code says before it is spent.

type CodeResult

type CodeResult struct {
	Label     string    `json:"label,omitempty"`
	ExpiresAt time.Time `json:"expires_at"`
}

CodeResult is the answer to a peek at a code.

func PeekCode

func PeekCode(ctx context.Context, hc *http.Client, base, code string) (CodeResult, error)

PeekCode asks what a code is for, without spending it.

type Credential

type Credential struct {
	ID          string
	WorkspaceID string
	Tenant      string
	Stack       string
	Name        string
	PublicKey   ed25519.PublicKey
	Fingerprint string
	Label       string
	OS          string
	Root        string
	Machine     string
	CreatedAt   time.Time
	RevokedAt   *time.Time
}

Credential is one key enrolled for exactly one workspace.

func (*Credential) Revoked

func (c *Credential) Revoked() bool

Revoked reports whether the credential may no longer hold its workspace.

func (*Credential) Spec

func (c *Credential) Spec() workspace.Spec

Spec is the workspace the credential names.

type EnrollBody

type EnrollBody struct {
	Code      string `json:"code"`
	PublicKey []byte `json:"public_key"` // the 32-byte Ed25519 key
	OS        string `json:"os,omitempty"`
	Root      string `json:"root,omitempty"`
	Machine   string `json:"machine,omitempty"`
}

EnrollBody is what a machine posts to enroll.

type EnrollResult

type EnrollResult struct {
	Credential string `json:"credential"`
	Name       string `json:"name"`
	Label      string `json:"label,omitempty"`
}

EnrollResult is the answer to an enrollment.

func EnrollKey

func EnrollKey(ctx context.Context, hc *http.Client, base string, key ed25519.PrivateKey, in EnrollBody) (EnrollResult, error)

EnrollKey spends code and enrolls key for the code's workspace. The request is signed with key itself, over its exact body: possession of the private half is proved at the moment the public half is enrolled.

type Enrollment

type Enrollment struct {
	PublicKey ed25519.PublicKey
	Label     string
	OS        string
	Root      string
	Machine   string
}

Enrollment is what a machine says of itself when it enrolls. Only the key decides anything; the rest is shown back to the owner.

type Envelope

type Envelope struct {
	WorkspaceID string `json:"workspace_id"`
	// Conn and Gen are the link the sender read in the claim. The holding
	// node forwards only to exactly that link.
	Conn   string `json:"conn"`
	Gen    int64  `json:"gen"`
	Header Header `json:"header"`
	// WaitMS is how long the holding node may wait for the machine: the
	// sender's own patience, less the hop back. A duration, so two nodes'
	// clocks need not agree.
	WaitMS int64 `json:"wait_ms"`
}

Envelope is one header on its way to a link on another node.

type ExecPayload

type ExecPayload struct {
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	Stdin   []byte            `json:"stdin,omitempty"`
	Cwd     string            `json:"cwd,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
	// TimeoutMS is the command's life: the whole of a held exec, or a
	// detached job's own deadline.
	TimeoutMS int64 `json:"timeout_ms,omitempty"`
	Detach    bool  `json:"detach,omitempty"`
}

ExecPayload is a request's payload today: one workspace exec.

type ExecReply

type ExecReply struct {
	Exit            int    `json:"exit"`
	Stdout          string `json:"stdout,omitempty"`
	Stderr          string `json:"stderr,omitempty"`
	StdoutTruncated bool   `json:"stdout_truncated,omitempty"`
	StderrTruncated bool   `json:"stderr_truncated,omitempty"`
	WallMS          int64  `json:"wall_ms,omitempty"`
	Job             string `json:"job,omitempty"`
	// Stopped: a detached job ended because it was asked to.
	Stopped bool       `json:"stopped,omitempty"`
	Error   *WireError `json:"error,omitempty"`
}

ExecReply is what the machine's `_attach` stack answers: an exec's result, the job a detached exec left running, or a coded error.

type HTTP

type HTTP struct {
	Svc *Service
	// ClientIP names the caller for the throttle: the socket peer, or what a
	// trusted edge says (edgeproxy.Clients.IP). nil uses RemoteAddr.
	ClientIP func(*http.Request) string
	// contains filtered or unexported fields
}

HTTP serves the machine-facing routes.

func NewHTTP

func NewHTTP(svc *Service, guessesPerMinute int) *HTTP

NewHTTP builds the handlers. A caller gets guessesPerMinute tries at a code a minute (0: 10).

func (*HTTP) Register

func (h *HTTP) Register(mux *http.ServeMux)

Register adds the routes to mux.

type Handler

type Handler interface {
	// Request does the work in h.Payload and returns the reply. ctx ends at
	// the request's deadline, or sooner when the chassis cancels it.
	Request(ctx context.Context, h Header) Reply
	// Stop asks a detached job to end.
	Stop(ctx context.Context, job string) error
}

Handler is what the machine does with what comes down the link. The link itself runs nothing: it carries a request to the handler and the answer back.

type Header struct {
	Kind string `json:"kind"`

	// hello
	Credential string `json:"credential,omitempty"`
	Machine    string `json:"machine,omitempty"`
	Root       string `json:"root,omitempty"`
	OS         string `json:"os,omitempty"`
	Version    string `json:"version,omitempty"`

	// request, cancel
	ID string `json:"id,omitempty"`
	// WithinMS is how long the machine has to answer, counted from when it
	// reads the request. A duration, never a time of day: the machine's
	// clock is its owner's, and may be minutes off.
	WithinMS int64 `json:"within_ms,omitempty"`
	// A request made by an async op carries that op's continuation. The
	// machine sends both back, unchanged, with the job's end (complete).
	OPC   string `json:"opc,omitempty"`
	Token string `json:"token,omitempty"`

	// stop, and the job a completion is for
	Job string `json:"job,omitempty"`

	// bye
	Reason string `json:"reason,omitempty"`

	// request: the work. complete: the result.
	Payload json.RawMessage `json:"payload,omitempty"`
}

Header opens a stream.

type Hub

type Hub struct {

	// Complete receives a detached job's end from a machine: the result of
	// the async op whose continuation the machine was handed. It returns
	// only once the result is durably recorded, because its return is what
	// lets the machine delete its copy. nil refuses completions.
	Complete func(ctx context.Context, cred *Credential, opc, token string, result json.RawMessage) error

	// Notify tells another node that a connection it holds was replaced.
	// nil on a single node. Best effort: the replaced connection can do
	// nothing in the meantime, since every request re-reads the claim.
	Notify func(ctx context.Context, node, workspaceID, conn, reason string)

	// Logf, when set, receives one line per link event.
	Logf func(format string, args ...any)
	// contains filtered or unexported fields
}

Hub is this node's side of every link it holds: it runs the handshake, keeps the claim, and forwards requests down to the machine.

func NewHub

func NewHub(store *Store, claims *Claims, node string) *Hub

NewHub builds the hub for the node named node. That name is what a claim records, and what other nodes address a request to.

func (*Hub) Close

func (h *Hub) Close(workspaceID, conn, reason string) bool

Close ends the link holding workspaceID here, if one does and it is conn (any, when conn is ""). It reports whether a link was closed.

func (*Hub) CloseAll

func (h *Hub) CloseAll(reason string)

CloseAll ends every link this node holds: the node is going down.

func (*Hub) Node

func (h *Hub) Node() string

Node is this hub's name.

func (*Hub) Send

func (h *Hub) Send(ctx context.Context, workspaceID, conn string, gen int64, hdr Header) (Reply, error)

Send forwards hdr to the machine on the link (workspaceID, conn, gen) and returns its reply. It is called on the node that holds the link.

BEFORE anything reaches the machine it checks, in this order:

  1. the credential, in the DB, is not revoked. This is what makes a revoke effective: from the moment it commits, nothing more is forwarded;
  2. the claim, in the KV, still names this connection and generation. A link that was replaced and not yet told can never take a request;
  3. the request's id is new.

These are read for every request, never cached: the machine is about to be handed a run's environment.

The error says what the caller may conclude. CodeAway: nothing was delivered. CodeUnknown: it may have been, and must not be sent again.

func (*Hub) Serve

func (h *Hub) Serve(ctx context.Context, rw io.ReadWriteCloser, host string) error

Serve runs one link from its handshake to its end. rw is the connection the machine dialed; host is the name the machine dialed it by, as this chassis saw it. It returns when the link is over, for any reason.

type Link struct {
	Credential string
	Key        ed25519.PrivateKey
	// Host is the name this machine dialed. It is signed into the
	// challenge, so an answer cannot be relayed to another host.
	Host string
	// What the machine says of itself. Shown to the owner on the chassis's
	// side; decides nothing.
	Machine, Root, OS, Version string

	Handler Handler
	// OnWelcome, when set, is called once the chassis has accepted the link.
	OnWelcome func(Welcome)
	// contains filtered or unexported fields
}

Link is the machine's side of one credential's connection.

func (*Link) Complete

func (l *Link) Complete(ctx context.Context, h Header) error

Complete sends a detached job's end up the link and returns nil once the chassis has acknowledged it — which it does only after recording the result durably. Until then the caller keeps its copy and sends again, on this connection or the next.

func (*Link) Run

func (l *Link) Run(ctx context.Context, rw io.ReadWriteCloser) error

Run serves one connection, from the handshake until it ends. It returns a *Refused when the chassis said why, and the connection's own error otherwise. Requests still running when it ends are cancelled; detached jobs are not this link's to end, and run on.

type LocalHandler

type LocalHandler interface {
	Forward(ctx context.Context, env Envelope) (Reply, error)
	Notify(n Notice)
}

LocalHandler is what a Relay backend calls for what arrives at THIS node. It reaches only links this node holds, never the relay, so a request cannot bounce between nodes.

type Notice

type Notice struct {
	WorkspaceID string `json:"workspace_id"`
	Conn        string `json:"conn"`
	Reason      string `json:"reason"`
}

Notice says a link is over, and why.

type Refused

type Refused struct{ Reason string }

Refused is a link the chassis turned away or closed, with its reason. A machine told ReasonReplaced or ReasonRevoked stops serving the credential: it does not dial again.

func (*Refused) Error

func (r *Refused) Error() string

type Relay

type Relay interface {
	// Forward delivers env to node and returns the reply of the link there.
	// Its error says what the caller may conclude, as Hub.Send's does:
	//
	//   - CodeAway: nothing was delivered. Nothing answers for that node, or
	//     the node refused before anything reached the machine.
	//   - CodeUnknown: the request left this node and no answer came back
	//     in time. The machine may have it.
	Forward(ctx context.Context, node string, env Envelope) (Reply, error)
	// Notify tells node that a link it holds is over. Best effort, and
	// nothing depends on it: a link that was replaced or revoked is refused
	// every request whether or not its node has heard.
	Notify(ctx context.Context, node string, n Notice) error
	// Shutdown stops answering for this node and releases the bus, bounded
	// by ctx.
	Shutdown(ctx context.Context) error
}

Relay is the hop between nodes: it carries a header from the node that runs an op to the node that holds the machine's link, and that node's reply back. The bundled chassis defines the seam and ships no backend; a build with a message bus registers one. On a single node there is none, and a link held elsewhere cannot exist.

It mirrors the WebSocket relay (personality/websocket/relay.go): the interface and the registry here, a backend self-registered by init() and a blank import, its connection details in its own environment. Which node holds a link is not the relay's question: the claim in the shared KV says so. The relay addresses a node and waits for its one answer.

func OpenRelay

func OpenRelay(name string, cfg RelayConfig) (Relay, error)

OpenRelay constructs the named backend. An unknown name is an error that lists what there is.

type RelayAnswer

type RelayAnswer struct {
	Reply Reply      `json:"reply"`
	Error *WireError `json:"error,omitempty"`
}

RelayAnswer is what a backend sends back for a Forward: the link's reply, or the coded error the holding node returned. One of the two.

func RelayAnswerOf

func RelayAnswerOf(rep Reply, err error) RelayAnswer

RelayAnswerOf packs a local Forward's outcome for the wire.

func (RelayAnswer) Fit

func (a RelayAnswer) Fit(max int) RelayAnswer

Fit shrinks an answer to at most max bytes of JSON, for a bus with a payload limit. Only an exec's two outputs can be large, so those are what is cut, and the cut is flagged as an exec's own caps flag theirs. An answer that still does not fit is replaced by an error saying so.

func (RelayAnswer) Result

func (a RelayAnswer) Result() (Reply, error)

Result unpacks a RelayAnswer on the sending node.

type RelayConfig

type RelayConfig struct {
	// NodeID names this chassis: the name its claims record, and so the
	// name other nodes address it by.
	NodeID  string
	Logger  *zap.Logger
	Handler LocalHandler
}

RelayConfig carries what a backend cannot find out for itself.

type RelayConstructor

type RelayConstructor func(cfg RelayConfig) (Relay, error)

RelayConstructor builds a Relay: it connects, subscribes this node's inbox, and wires what arrives to cfg.Handler.

type Reply

type Reply struct {
	OK      bool            `json:"ok"`
	Error   *WireError      `json:"error,omitempty"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

Reply closes a stream the chassis opened, or acknowledges one the machine opened.

type Service

type Service struct {
	Store  *Store
	Claims *Claims
	Hub    *Hub

	// Forward sends a header to the node that holds a link and returns its
	// reply: the cross-node hop. nil on a single node, where a link held
	// elsewhere cannot exist. It must answer CodeAway when the node is not
	// there to take it, and CodeUnknown when it took it and never replied.
	Forward func(ctx context.Context, node, workspaceID, conn string, gen int64, hdr Header) (Reply, error)

	// PublicURL is where machines dial this chassis, scheme and host. A
	// code is answered with its host appended, so `txco attach <code>`
	// knows where to go. Empty answers the code bare.
	PublicURL string
	// contains filtered or unexported fields
}

Service is attach as the rest of the chassis sees it: the answer for attached names (workspace.Attached), and the invite, status, revoke and stop behind the txco://attach ops.

func NewService

func NewService(store *Store, claims *Claims, node string) *Service

NewService wires the three parts for the node named node.

func (*Service) Enroll

func (s *Service) Enroll(ctx context.Context, code string, e Enrollment) (*Credential, error)

Enroll spends code and makes e's key the workspace's one credential. An earlier credential for the name is revoked in the same transaction; its link, if it has one, is then closed. That closing is a courtesy: the old machine is already refused every request.

func (*Service) Invite

func (s *Service) Invite(ctx context.Context, spec workspace.Spec, label string, ttl time.Duration) (code string, expires time.Time, err error)

Invite makes a one-use code for the workspace.

func (*Service) Local

func (s *Service) Local() LocalHandler

Local is this node's side of the relay: what a backend hands inbound requests to.

func (*Service) Release

func (s *Service) Release(ctx context.Context, spec workspace.Spec, credential string) error

Release implements workspace.Attached: the workspace is being destroyed. The credential is revoked, the claim cleared (keeping its generation) and the link, wherever it is, closed. The Manager then marks the row destroyed, and the name is the provider's again.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, spec workspace.Spec) error

Revoke revokes the workspace's credential. The row stays attached, so the name reads away and is not handed back to the provider.

func (*Service) SetRelay

func (s *Service) SetRelay(r Relay)

SetRelay gives the service its hop between nodes. Call it before the service takes requests.

func (*Service) Shutdown

func (s *Service) Shutdown(ctx context.Context) error

Shutdown releases the relay, if there is one.

func (*Service) Status

func (s *Service) Status(ctx context.Context, spec workspace.Spec) (Status, error)

Status reports on one workspace. The DB says whether it is enrolled; the KV, only whether its machine is here now.

func (*Service) Stop

func (s *Service) Stop(ctx context.Context, spec workspace.Spec, job string) error

Stop asks the machine to end a detached job.

func (*Service) Wake

func (s *Service) Wake(ctx context.Context, spec workspace.Spec, credential string) (workspace.Computer, error)

Wake implements workspace.Attached. The Manager has already read the row: the name IS attached. Whether a machine is connected is this call's question, and no connected machine is CodeAway — never the provider.

type Status

type Status struct {
	// Enrolled: the row says a machine holds the name (true after a revoke
	// too, until the workspace is destroyed).
	Enrolled bool `json:"enrolled"`
	// Attached: a machine is connected right now.
	Attached bool      `json:"attached"`
	Since    time.Time `json:"since,omitzero"`
	Machine  string    `json:"machine,omitempty"`
	Root     string    `json:"root,omitempty"`
	OS       string    `json:"os,omitempty"`
	Version  string    `json:"version,omitempty"`
}

Status is what txco://attach/status answers.

type Store

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

Store is the durable half of attach: codes, credentials, and the workspace row that says a name is attached. It lives in the runtime DB.

func NewStore

func NewStore(db *sql.DB, d registry.Dialect) *Store

NewStore builds a Store over the opened runtime DB. A nil dialect is SQLite.

func (*Store) CreateCode

func (s *Store) CreateCode(ctx context.Context, spec workspace.Spec, label string, ttl time.Duration) (code string, expires time.Time, err error)

CreateCode makes a one-use code for the workspace spec names and returns it, once: only its hash is kept. It refuses a name the provider holds, so the owner hears of it now and not on their machine.

func (*Store) Credential

func (s *Store) Credential(ctx context.Context, id string) (*Credential, error)

Credential returns the credential by id, revoked or not; (nil, nil) when there is none. This is the read the holder makes before every request: the DB, each time, never a copy kept in memory.

func (*Store) Enroll

func (s *Store) Enroll(ctx context.Context, code string, e Enrollment) (cred *Credential, replaced []string, err error)

Enroll spends code and makes its key the one credential for the code's workspace. In ONE transaction:

  • the code is spent, by an UPDATE that must touch exactly one row;
  • a name the provider holds is refused (and the code is not spent);
  • any earlier credential for the workspace is revoked;
  • the new credential is written;
  • the workspace's row becomes the attached provider's.

The caller must already have verified that the request was signed by e.PublicKey over these exact bytes. Enroll trusts its arguments.

func (*Store) Enrolled

func (s *Store) Enrolled(ctx context.Context, spec workspace.Spec) (enrolled bool, cred *Credential, err error)

Enrolled reports whether the workspace's row says a machine holds the name, and the live credential if there is one (none after a revoke).

func (*Store) EnsureSchema

func (s *Store) EnsureSchema(ctx context.Context) error

EnsureSchema creates the attach tables if absent. Prod gets them from the runtime migration (0031 / the overlay's own); this is for tests and for a chassis that opens the DB without the migration runner.

func (*Store) Live

func (s *Store) Live(ctx context.Context, workspaceID string) (*Credential, error)

Live returns the one unrevoked credential for a workspace; (nil, nil) when there is none.

func (*Store) PeekCode

func (s *Store) PeekCode(ctx context.Context, code string) (*CodeInfo, error)

PeekCode reads a live code without spending it, so `txco attach` can say what it is about to attach to before the owner accepts.

func (*Store) Revoke

func (s *Store) Revoke(ctx context.Context, workspaceID string) (string, error)

Revoke revokes the workspace's live credential and returns its id ("" when there was none). The row stays attached, so the name reads away, and is not handed back to the provider until the workspace is destroyed.

From the moment this commits no request is forwarded to the machine: the holder reads the credential before each one.

type Welcome

type Welcome struct {
	OK     bool   `json:"ok"`
	Reason string `json:"reason,omitempty"`
	Gen    int64  `json:"gen,omitempty"`
	// What the credential is for, as the chassis recorded it. Shown to the
	// owner; decides nothing.
	Label string `json:"label,omitempty"`
	Name  string `json:"name,omitempty"`
}

Welcome ends the handshake.

type WireError

type WireError struct {
	Code    string `json:"code"`
	Message string `json:"message,omitempty"`
}

WireError is a coded failure on the wire: a workspace.Error's two fields.

Directories

Path Synopsis
Package home is the one folder `txco attach` keeps on a machine:
Package home is the one folder `txco attach` keeps on a machine:

Jump to

Keyboard shortcuts

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