Documentation
¶
Overview ¶
Package pluginhost runs external Sidecar plugins: it owns the process boundary, the protocol envelope, the compiled matcher snapshot, and the host-side cache and concurrency policy.
It speaks two dialects through one manager, one cache, and one process policy. An instance configured under terminalResources is dispatched with the frozen sidecar.terminal-resource/v1 identifier and answers describe and resolve; an instance configured under plugins.external is dispatched with sidecar.plugin/v1 and additionally answers list, get, and act. Both end up as the same host types, because the second protocol is the first one grown rather than a replacement.
Two seams, each narrow on purpose:
- Provider is the in-process adapter the Manager consumes. CommandProvider is the default implementation; tests use an in-memory fake; a future resident transport implements the same methods. PluginProvider is the optional extension a plugin-protocol instance also satisfies.
- The executable protocol is the language-agnostic boundary. It returns declarations and data, never a Sidecar interface.
A process boundary is crash isolation, not a sandbox. Enabling a plugin trusts that executable with the user's full OS privileges.
See docs/reference/plugin-protocol.md and docs/reference/terminal-resource-provider-protocol.md.
Index ¶
- Constants
- Variables
- func AsResourceError(err error) *resource.Error
- func BuildEnv(passEnv []string, host []string) []string
- func CallTimeout(configured time.Duration) time.Duration
- func ClampListLimit(limit int) int
- func ClampRefreshSeconds(seconds int) int
- func FilterCacheKey(applied map[string]string) string
- func FilterKeys(applied map[string]string) []string
- func NormalizeFilters(c Collection, applied map[string]string) map[string]string
- func OutcomeCode(err error) string
- type ActParams
- type ActRequest
- type ActStatus
- type Action
- type ActionInput
- type ActionTarget
- type Align
- type Collection
- type Column
- type ColumnKind
- type CommandConfig
- type CommandProvider
- func (p *CommandProvider) Act(ctx context.Context, params ActParams, callCtx *Context) (Outcome, error)
- func (p *CommandProvider) Argv() []string
- func (p *CommandProvider) ClaimHosts() []string
- func (p *CommandProvider) Describe(ctx context.Context) (Description, error)
- func (p *CommandProvider) Env() []string
- func (p *CommandProvider) Get(ctx context.Context, params GetParams, callCtx *Context, collection Collection) (resource.Document, error)
- func (p *CommandProvider) Instance() string
- func (p *CommandProvider) List(ctx context.Context, params ListParams, callCtx *Context, ...) (Page, error)
- func (p *CommandProvider) Protocol() string
- func (p *CommandProvider) Resolve(ctx context.Context, ref resource.Reference) (resource.Document, error)
- func (p *CommandProvider) ResolveTimeout() time.Duration
- func (p *CommandProvider) ResolvedCommand() (argv []string, path string)
- func (p *CommandProvider) SpeaksPluginProtocol() bool
- type CompiledMatcher
- type Context
- type ContextKind
- type Coverage
- type CoverageState
- type DescribedSet
- type Description
- type ExecRunner
- type Filter
- type FilterKind
- type FilterOption
- type GetParams
- type GetRequest
- type HostInfo
- type Info
- type InputKind
- type Item
- type ListParams
- type ListRequest
- type Manager
- func (m *Manager) Act(ctx context.Context, req ActRequest) (Outcome, error)
- func (m *Manager) CancelPane(paneKey string)
- func (m *Manager) Collection(instance, collection string) (Collection, bool)
- func (m *Manager) DescribeAll(ctx context.Context) []Status
- func (m *Manager) Description(instance string) (Description, bool)
- func (m *Manager) Get(ctx context.Context, req GetRequest) (resource.Document, error)
- func (m *Manager) List(ctx context.Context, req ListRequest) (Page, error)
- func (m *Manager) Resolve(ctx context.Context, ref resource.Reference, refresh bool) (resource.Document, error)
- func (m *Manager) SetProviders(providers []Provider, disabled []string)
- func (m *Manager) Snapshot() *Snapshot
- func (m *Manager) SnapshotError() error
- func (m *Manager) Status(instance string) (Status, bool)
- func (m *Manager) Statuses() []Status
- type ManagerOptions
- type Matcher
- type Notice
- type Omitted
- type OpenTarget
- type Options
- type Outcome
- type Page
- type PageOutcome
- type PluginProvider
- type ProjectContext
- type Provider
- type Refresh
- type Request
- type ResolveParams
- type Response
- type RunResult
- type RunSpec
- type Runner
- type SearchMode
- type SelectionContext
- type Snapshot
- func (s *Snapshot) ClaimHosts(instance string) []string
- func (s *Snapshot) Generation() uint64
- func (s *Snapshot) Len() int
- func (s *Snapshot) Lookup(instance, id string) (CompiledMatcher, bool)
- func (s *Snapshot) Matchers() []CompiledMatcher
- func (s *Snapshot) TerminalMatchers() []terminallink.ResourceMatcher
- type SnapshotStore
- type SortDir
- type SortKey
- type SortOrder
- type State
- type Status
- type TransportError
- type TransportReason
- type View
- type WireAction
- type WireActionInput
- type WireCollection
- type WireColumn
- type WireCoverage
- type WireFilter
- type WireFilterChoice
- type WireItem
- type WireNotice
- type WireOmitted
- type WireOpen
- type WireOutcome
- type WirePage
- type WireRefresh
- type WireSortKey
- type WireView
Constants ¶
const ( DefaultMaxConcurrent = 4 DefaultMaxConcurrentPerProvider = 2 )
Default concurrency caps. They are small on purpose: a provider invocation is a process spawn, and on a machine with an endpoint security agent every spawn carries a large fixed tax. Excess work queues and stays cancellable.
const ( MethodDescribe = "describe" MethodResolve = "resolve" MethodList = "list" MethodGet = "get" MethodAct = "act" )
Method names. An unknown method must return an internal error rather than crash the plugin; the host never sends one.
const ( // MaxCollections bounds how many collections one plugin may declare. MaxCollections = 16 // MaxColumns bounds one collection's column list. MaxColumns = 12 // MaxViews and MaxSortKeys bound one collection's view pills and sort keys. MaxViews = 32 MaxSortKeys = 16 // MaxFilters bounds one collection's declared choosers. Eight is what the // View modal can draw without becoming a page of its own, and the first of // them is the collection's scope. MaxFilters = 8 // MaxFilterChoices bounds one choice filter's option list. MaxFilterChoices = 64 // MaxFilterIDChars and MaxFilterTitleChars bound a filter's identity and // the strings the host paints for it. They are short because a filter id // rides in persisted tab state and a filter title rides in the View pill. MaxFilterIDChars = 32 MaxFilterTitleChars = 32 // MaxFilterValueChars bounds a text filter's value — the initial text a // plugin declares and the value the host sends back. It is bounded on both // sides because the value is persisted with the tab. MaxFilterValueChars = 64 // MaxCoverageRows and MaxCoverageReasonChars bound the per-source ledger a // page may carry. It is read only by the coverage modal; the notices stay // the one-line summary. MaxCoverageRows = 64 MaxCoverageReasonChars = 200 // MaxCoverageSourceChars bounds one coverage row's source name. MaxCoverageSourceChars = 64 // MaxActions bounds a plugin's action list and MaxActionInputs one // action's form. MaxActions = 32 MaxActionInputs = 8 // MaxActionChoices bounds a choice input's option list. It is not in the // protocol table: a choice list is a menu the host has to draw, and an // unbounded one is a frame that never finishes. MaxActionChoices = 64 // MaxPageItems bounds one page and clamps the requested limit. MaxPageItems = 500 // MaxCellChars bounds one table cell. MaxCellChars = 512 // StatusLabelRenderChars is how much of a row's status.label the host will // ever draw: the reserved status column never grows past it, and a longer // label is truncated into it. // // It is a RENDER bound, not a wire bound. resource.MaxStatusLabelChars is // frozen at 64 and stays exactly where it is — a longer label is still // accepted, sanitized, and carried, and a plugin that sends one is not // wrong. It simply cannot be read past this width, which is what the // protocol reference states so a plugin author can choose a label that // fits rather than discovering the truncation in a pane. StatusLabelRenderChars = 24 // MaxNotices and MaxNoticeChars bound the notice rows above a list. MaxNotices = 4 MaxNoticeChars = 200 // MaxWatchPaths bounds a plugin's declared refresh paths. MaxWatchPaths = 8 // MinRefreshSeconds and MaxRefreshSeconds clamp a declared poll interval. MinRefreshSeconds = 15 MaxRefreshSeconds = 900 // MaxCollectionIDChars, MaxTitleChars and MaxColumnLabelChars bound the // identifiers and labels the host paints. IDs are persisted in pane state, // which is why they are bounded at all. MaxCollectionIDChars = 64 MaxCollectionTitle = 64 MaxColumnIDChars = 64 MaxColumnLabelChars = 32 MaxColumnWidth = 200 // MaxActionIDChars and MaxActionTitleChars bound an action's identity and // its menu row. MaxActionIDChars = 64 MaxActionTitleChars = 64 // MaxInputChars bounds an input's label and its default value. MaxInputLabelChars = 64 MaxInputDefaultChars = 512 // MaxOutcomeMessageChars bounds the single line an act flashes. MaxOutcomeMessageChars = 200 // MaxRefreshCollections bounds how many collections one outcome may ask to // re-list. MaxRefreshCollections = MaxCollections )
The plugin protocol's Limits table. Everything in resource v1's table still applies; these are the bounds the new vocabulary adds. They are host choices the protocol document points back at, so changing one changes the contract.
const PluginMarker = "SIDECAR_PLUGIN=1"
PluginMarker is the one variable the host sets rather than inherits, so a tool whose ordinary CLI and whose plugin subcommand share a binary can tell which one it is running as.
It is added only for the plugin protocol. The frozen resource protocol publishes its child environment exactly, and adding a variable to it would change a contract that is closed.
const Protocol = "sidecar.plugin/v1"
Protocol is the plugin contract this host speaks. It is frozen, the way sidecar.terminal-resource/v1 is: the host implemented it, one real external plugin implemented it against a live tool, and both revised from what the other found before the identifier stopped moving.
The host sends this value and validates the answer against it strictly. It accepts no alias: a plugin answering the pre-freeze draft identifier is a protocol failure here, because tolerance belongs on the plugin side. A plugin that accepts either identifier on a request and answers with whichever it was asked keeps working with an older Sidecar and with this one, and the host's rule stays literally true.
The frozen resource identifier lives in internal/resource and is unchanged. One host speaks both: an instance configured under terminalResources is dispatched with resource.Protocol, an instance configured under plugins.external with this one, and the answer is translated into the same host types either way.
Variables ¶
var HostVersion = "0.0.0"
HostVersion identifies Sidecar to plugins. The app sets it once at startup; until then plugins see the placeholder the protocol examples use.
Functions ¶
func AsResourceError ¶
AsResourceError turns any error from a Provider into the typed error a view can render. A provider's own typed failure passes through unchanged; a transport failure is mapped; anything else is internal.
func BuildEnv ¶
BuildEnv returns the complete environment for one invocation: the documented base, plus the current values of the names in passEnv, and nothing else.
host is an os.Environ()-shaped slice, so a test can build an environment without touching the process's own and without a magic sentinel.
A passEnv entry is a name only. Sidecar never accepts an inline secret value in configuration, never logs a passed value, and never renders one — which is also why an entry containing "=" is refused rather than split.
The base set wins on conflict: naming PATH in passEnv cannot change the child's PATH. That falls out of adding the base first and add() being first-write-wins, which is the documented rule.
func CallTimeout ¶
CallTimeout is the per-call budget for list, get, act and resolve. describe has its own fixed, shorter budget because it is local and must be fast.
func ClampListLimit ¶
ClampListLimit brings a requested page size into range.
func ClampRefreshSeconds ¶
ClampRefreshSeconds brings a declared poll interval into range. Zero and negative mean "no polling" rather than "poll as fast as possible".
func FilterCacheKey ¶
FilterCacheKey renders an applied set as one canonical string, so two identical scopes are one cache entry and two different ones are two. It is the get cache's half of the rule that a row expanded under a filter-chosen scope is a different document from the same row expanded under another.
The separators are NUL, which resource.SanitizeLine strips from every value that reaches here, so no filter value can spell a different set.
func FilterKeys ¶
FilterKeys returns the applied filter IDs in a stable order, which is what a CLI report and a persisted record need so two identical states are two identical strings.
func NormalizeFilters ¶
func NormalizeFilters(c Collection, applied map[string]string) map[string]string
NormalizeFilters is the one place the wire rule for params.filters is enforced, so the browser, the CLI and the process boundary cannot disagree about what reaches a plugin:
- a key the collection did not declare is DROPPED, because the plugin has no control behind it and would be filtering on a name it never published;
- a choice value that is not one of that filter's declared options is dropped, for the same reason;
- a value equal to the filter's default is dropped, because a missing key means the default and sending it twice is two spellings of one state;
- everything else is sanitized to the declared bounds.
It returns nil rather than an empty map when nothing survives, so the field is omitted from the request entirely.
func OutcomeCode ¶
OutcomeCode is the single token a log line records for an invocation. It is either "ok", a typed error code, or a transport reason — never a message.
Types ¶
type ActParams ¶
type ActParams struct {
Action string `json:"action"`
Collection string `json:"collection,omitempty"`
ID string `json:"id,omitempty"`
Matcher string `json:"matcher,omitempty"`
Locator string `json:"locator,omitempty"`
Inputs map[string]string `json:"inputs,omitempty"`
}
ActParams addresses one action. A collection or item action carries collection+id; a resource action carries matcher+locator instead, which is how "transition this ticket" fits without a sixth method.
type ActRequest ¶
ActRequest addresses one act call.
type ActStatus ¶
type ActStatus string
ActStatus is whether an action succeeded.
func CoerceActStatus ¶
CoerceActStatus maps a declared status onto a known one. An unrecognised status is a failure: an action whose result the host cannot read must not be reported to the user as having worked.
type Action ¶
type Action struct {
ID string
Title string
On ActionTarget
// Collection is the collection this applies to, required for item and
// collection actions and empty otherwise.
Collection string
Inputs []ActionInput
Mutates bool
// Confirm is the resolved answer, not the declared one: a mutating action
// with no inputs confirms unless the plugin said confirm:false, and an
// action with inputs does not, because its form is the confirm step.
Confirm bool
// Key is a single lowercase letter the plugin asked for. It is a request,
// never a grant: the host clears it when its own reserved set or the
// surface's bindings already use that key, and it is never persisted.
Key string
}
Action is a typed operation the user can invoke. The plugin declares it; the host decides how it is reached. Actions never carry code, keys the host did not grant, or colours.
type ActionInput ¶
type ActionInput struct {
ID string
Label string
Kind InputKind
Required bool
Choices []string
Default string
}
ActionInput is one field of an action's form.
type ActionTarget ¶
type ActionTarget string
ActionTarget is what an action applies to.
const ( // ActionOnItem applies to one collection row. ActionOnItem ActionTarget = "item" // ActionOnCollection applies to the whole list. ActionOnCollection ActionTarget = "collection" // ActionOnResource applies to a matcher-resolved document. ActionOnResource ActionTarget = "resource" // ActionOnGlobal has no subject. ActionOnGlobal ActionTarget = "global" )
func CoerceActionTarget ¶
func CoerceActionTarget(v string) ActionTarget
CoerceActionTarget maps a declared target onto a known one, or "" for one the host does not know — which validation refuses rather than guessing at.
type Align ¶
type Align string
Align is a column's horizontal alignment.
func CoerceAlign ¶
CoerceAlign maps a declared alignment onto a known one.
type Collection ¶
type Collection struct {
ID string
Title string
Search SearchMode
Columns []Column
Views []View
Sort []SortKey
// Filters are the collection's declared choosers, in declared order. The
// first is the collection's scope, whose current value the host always
// shows.
Filters []Filter
// Detail reports whether get is meaningful for rows.
Detail bool
Refresh Refresh
// Context narrows the collection: ["project"] means it is meaningful only
// where project context exists, so a global surface hides it.
Context []ContextKind
}
Collection is a named, listable set of rows the host shows as a table with a cursor.
func (Collection) Filter ¶
func (c Collection) Filter(id string) (Filter, bool)
Filter returns one declared filter by ID.
func (Collection) PrimaryColumn ¶
func (c Collection) PrimaryColumn() (Column, bool)
PrimaryColumn returns the column that names a row.
func (Collection) ScopeFilter ¶
func (c Collection) ScopeFilter() (Filter, bool)
ScopeFilter is the collection's scope: the first declared filter, which is what the pill always carries.
type Column ¶
type Column struct {
ID string
Label string
// Width is a hint in cells; the host reflows. Zero means no hint.
Width int
Align Align
Kind ColumnKind
// Primary names the row. Exactly one column is primary; validation
// promotes the first column when the plugin named none.
Primary bool
// Secondary is folded under the primary line when the pane is too narrow
// for a table. At most one column is secondary.
Secondary bool
}
Column is one table column.
type ColumnKind ¶
type ColumnKind string
ColumnKind decides how the host renders a cell.
const ( ColumnText ColumnKind = "text" ColumnStatus ColumnKind = "status" ColumnTimestamp ColumnKind = "timestamp" ColumnUser ColumnKind = "user" ColumnNumber ColumnKind = "number" ColumnBadge ColumnKind = "badge" )
func CoerceColumnKind ¶
func CoerceColumnKind(v string) ColumnKind
CoerceColumnKind maps a declared kind onto a known one; anything else is plain text, which every kind degrades to safely.
type CommandConfig ¶
type CommandConfig struct {
Instance string
Argv []string
// Dir is the neutral working directory — a Sidecar config directory, never
// a selected repository.
Dir string
// PassEnv names variables whose current values are inherited on top of the
// documented base environment.
PassEnv []string
// ClaimHosts is the instance configuration's claimed hostnames, already
// validated and lowercased by internal/config. It is host-side data: it
// never reaches the child process or the protocol.
ClaimHosts []string
// HostEnv is the os.Environ()-shaped environment to draw from.
HostEnv []string
// ResolveTimeout is clamped; zero takes the default.
ResolveTimeout time.Duration
// Runner defaults to ExecRunner.
Runner Runner
// Host identifies Sidecar to the provider.
Host HostInfo
// Log receives metadata-only invocation records. Nil discards them.
Log *slog.Logger
// Protocol is the wire identifier to dispatch with. Empty means the frozen
// resource protocol, so an existing caller keeps the behaviour it had.
Protocol string
// Home bounds declared watch paths. Empty resolves from HostEnv's HOME and
// then from the OS, once, here — never on an invocation path.
Home string
}
CommandConfig is everything a CommandProvider needs. It is resolved once, at construction, so no invocation reads configuration or the environment.
type CommandProvider ¶
type CommandProvider struct {
// contains filtered or unexported fields
}
CommandProvider is the default Provider: a short-lived child process per request, one JSON object in, one JSON object out. It also carries the instance configuration's claimed hosts, which are host-side data a provider process never sees.
func NewCommandProvider ¶
func NewCommandProvider(cfg CommandConfig) (*CommandProvider, error)
NewCommandProvider builds a provider over a configured argv.
func (*CommandProvider) Act ¶
func (p *CommandProvider) Act(ctx context.Context, params ActParams, callCtx *Context) (Outcome, error)
Act runs the act method and sanitizes the outcome. It is the only method that mutates, and the host never calls it without the user having confirmed.
func (*CommandProvider) Argv ¶
func (p *CommandProvider) Argv() []string
Argv exposes the resolved command for diagnostics. It is a copy.
func (*CommandProvider) ClaimHosts ¶
func (p *CommandProvider) ClaimHosts() []string
ClaimHosts reports the instance's claimed hostnames. It is a copy.
func (*CommandProvider) Describe ¶
func (p *CommandProvider) Describe(ctx context.Context) (Description, error)
Describe runs the describe method and validates the result.
func (*CommandProvider) Env ¶
func (p *CommandProvider) Env() []string
Env exposes the computed child environment for diagnostics. Values are real, so a caller that prints this must redact — `terminal-links check` reports names only.
func (*CommandProvider) Get ¶
func (p *CommandProvider) Get(ctx context.Context, params GetParams, callCtx *Context, collection Collection) (resource.Document, error)
Get runs the get method and sanitizes the document, sections included.
collection is the validated declaration, for the same reason List takes it: the applied filters are narrowed against it here, at the process boundary, so "a key the collection did not declare never reaches the plugin" is a property of the host rather than a promise every caller has to keep.
func (*CommandProvider) Instance ¶
func (p *CommandProvider) Instance() string
Instance reports the configured instance ID.
func (*CommandProvider) List ¶
func (p *CommandProvider) List(ctx context.Context, params ListParams, callCtx *Context, collection Collection) (Page, error)
List runs the list method and sanitizes the page.
A `search: required` collection with an empty query is answered here, without starting a process: the plugin has nothing to say until there is a query, and spawning a child to be told so once per keystroke is exactly the cost this protocol is trying not to pay.
func (*CommandProvider) Protocol ¶
func (p *CommandProvider) Protocol() string
Protocol reports the wire identifier this instance is dispatched with.
func (*CommandProvider) Resolve ¶
func (p *CommandProvider) Resolve(ctx context.Context, ref resource.Reference) (resource.Document, error)
Resolve runs the resolve method and sanitizes the document.
func (*CommandProvider) ResolveTimeout ¶
func (p *CommandProvider) ResolveTimeout() time.Duration
ResolveTimeout reports the clamped per-invocation timeout.
func (*CommandProvider) ResolvedCommand ¶ added in v1.15.0
func (p *CommandProvider) ResolvedCommand() (argv []string, path string)
ResolvedCommand reports the configured argv and the file argv[0] resolves to right now, or "" if it resolves to nothing.
The lookup is deliberately performed on call rather than cached at construction: PATH is the thing under suspicion whenever this is asked for, and a value frozen at startup would answer for a lookup nobody is debugging. It runs the same PATH resolution the Runner will, but spawns nothing, and the Manager only asks after a describe has already failed.
func (*CommandProvider) SpeaksPluginProtocol ¶
func (p *CommandProvider) SpeaksPluginProtocol() bool
SpeaksPluginProtocol reports whether list, get, and act are available on this instance.
type CompiledMatcher ¶
type CompiledMatcher struct {
// Instance is the configured provider instance ID.
Instance string
// ID is the provider-stable matcher ID stored in resource references.
ID string
// Pattern is the RE2 source, kept for diagnostics.
Pattern string
// Priority orders matchers within one provider; higher runs earlier.
Priority int
// Order is the instance's position in configuration, which is the outer
// precedence key.
Order int
// contains filtered or unexported fields
} // Regexp returns the compiled expression. The whole match is the locator.
CompiledMatcher is one live external matcher. It is immutable once built and carries its compiled RE2 so the scanner never compiles anything on a frame.
func (CompiledMatcher) Regexp ¶
func (m CompiledMatcher) Regexp() *regexp.Regexp
type Context ¶
type Context struct {
Project *ProjectContext `json:"project,omitempty"`
Selection *SelectionContext `json:"selection,omitempty"`
}
Context is what the host sends, and only for kinds the plugin declared.
type ContextKind ¶
type ContextKind string
ContextKind is a kind of host context a plugin declares that it reads. Declaring it in describe is what lets the settings page and `sidecar plugin list` show it before anything runs; configuring the plugin is the trust act, and there is no second per-field grant.
const ( // ContextProject is the surface's project: root, working directory, name, // branch, and the host ID when the surface is bound to another machine. ContextProject ContextKind = "project" // ContextSelection is the text the user had selected when they invoked an // action. ContextSelection ContextKind = "selection" )
func CoerceContextKind ¶
func CoerceContextKind(v string) ContextKind
CoerceContextKind returns the declared kind, or "" for anything this version does not know. Nothing else is a context kind in v1: terminal lines, scrollback, tmux targets, file contents, and the environment are not, and adding one is a protocol revision rather than a field.
type Coverage ¶
type Coverage struct {
Source string
State CoverageState
// Reason is the plugin's own one-line explanation, shown verbatim.
Reason string
// ElapsedMs is how long the source took. Zero means the plugin did not say.
ElapsedMs int
}
Coverage is one source's row in a page's per-source ledger. It is read only by the host's coverage modal; the notices stay the one-line summary, because thirteen sources' states do not fit in four notice rows and a reader who wants them is asking a second question.
type CoverageState ¶
type CoverageState string
CoverageState is what one source did when this page was gathered.
const ( // CoverageAnswered means the source answered in full. CoverageAnswered CoverageState = "answered" // CoverageTimeout means the source ran out of the budget it was given. CoverageTimeout CoverageState = "timeout" // CoverageUnhealthy means the source was reachable but could not be // trusted to answer — a stale checkpoint, a broken index. CoverageUnhealthy CoverageState = "unhealthy" // CoverageSkipped means the source was not asked at all. CoverageSkipped CoverageState = "skipped" // CoverageFailed means the source was asked and errored. CoverageFailed CoverageState = "failed" )
func CoerceCoverageState ¶
func CoerceCoverageState(v string) CoverageState
CoerceCoverageState maps a declared state onto a known one. An unknown state reads as failed for the same reason an unknown outcome reads as degraded: of the two ways to be wrong about a word the host cannot read, the one that does not invent a guarantee on the plugin's behalf is the honest one.
func (CoverageState) Tone ¶
func (s CoverageState) Tone() resource.Tone
Tone is the status tone the host paints a coverage state in. It is the host's mapping, not the plugin's: a plugin must not be able to colour its own failure green.
type DescribedSet ¶
type DescribedSet struct {
Instance string
Order int
Matchers []Matcher
// ClaimHosts is the instance configuration's claimed hostnames. It travels
// with the described matchers so a claimed URL is only ever reclassified by
// a matcher from this same set.
ClaimHosts []string
}
DescribedSet is one instance's contribution to a snapshot, in configured order.
type Description ¶
type Description struct {
Info Info
Matchers []Matcher
// Context is the kinds of host context the plugin declared it reads.
// Nothing outside this list is ever sent to it.
Context []ContextKind
// Collections are the listable sets of rows it offers.
Collections []Collection
// Actions are the typed operations it exposes.
Actions []Action
}
Description is a validated describe result. Reaching this type means every pattern compiled, every ID was unique, and every bound held.
The last three fields are the plugin protocol's; a resource provider leaves them empty, which is exactly what "a plugin that declares no collections and no actions is exactly a resource provider" means in the host.
func ValidateDescribe ¶
func ValidateDescribe(instance string, resp *Response, home string) (Description, error)
ValidateDescribe checks a plugin-protocol describe response whole: the identity block and matchers by the frozen resource rules, then the collections and actions this protocol adds.
It is all-or-nothing for the same reason ValidateDescription is. A plugin that declares one uncompilable pattern, one unrenderable collection, or one watch path outside the user's home has a bug the user needs to see, and publishing the rest of its declarations would hide that while changing what the scanner recognises and what the host is watching on disk. The refusal is a *TransportError with ReasonInvalidDescribe, which `sidecar plugin list --describe` prints verbatim.
home is the user's home directory, used to bound watch paths. An empty home means no watch path can be validated, so any declared one is refused.
func ValidateDescription ¶
func ValidateDescription(instance string, info *Info, matchers []Matcher) (Description, error)
ValidateDescription sanitizes and checks a describe response. It is all-or-nothing on purpose: a provider that declares one uncompilable pattern has a bug the user needs to see, and silently publishing its other matchers would hide it while changing what the scanner recognizes.
The returned Description is safe to publish; the returned error, when non-nil, is a *TransportError with ReasonInvalidDescribe.
func (Description) Action ¶
func (d Description) Action(id string) (Action, bool)
Action returns one declared action by ID.
func (Description) Collection ¶
func (d Description) Collection(id string) (Collection, bool)
Collection returns one declared collection by ID.
func (Description) ReadsContext ¶
func (d Description) ReadsContext(kind ContextKind) bool
ReadsContext reports whether the plugin declared it reads kind.
func (Description) WatchPaths ¶
func (d Description) WatchPaths() []string
WatchPaths returns every distinct path this plugin asked the host to watch, across all its collections. It is what the livepanes binding reads.
type ExecRunner ¶
type ExecRunner struct{}
ExecRunner runs a real child process in its own process group.
func (ExecRunner) Run ¶
Run starts the command, writes stdin, drains stdout and stderr concurrently into bounded sinks, and waits. On timeout or cancellation it kills the whole process group — so a forked descendant dies with it — then finishes draining and reaps.
Deliberately not exec.CommandContext: that kills only the direct child, which leaves a descendant holding the stdout pipe and hangs the drain forever.
type Filter ¶
type Filter struct {
ID string
Label string
Kind FilterKind
// Choices is the option list of a choice filter, and empty for a text one.
Choices []FilterOption
// Default is the choice ID a choice filter opens on, or the initial text of
// a text filter. A value equal to it is never sent: a missing key means the
// default.
Default string
}
Filter is one declared chooser on a collection.
func (Filter) DisplayValue ¶
DisplayValue is what the host shows for this filter's current setting: a choice's title, or a text filter's own value. A text filter with no value shows its label, because "since" says more than an empty string does.
func (Filter) OptionTitle ¶
OptionTitle returns the display title of one of a choice filter's options.
type FilterKind ¶
type FilterKind string
FilterKind is the shape of one filter's control.
const ( // FilterChoice is a fixed set of options drawn as a radio group. FilterChoice FilterKind = "choice" // FilterText is free text drawn as an input. FilterText FilterKind = "text" )
func CoerceFilterKind ¶
func CoerceFilterKind(v string) FilterKind
CoerceFilterKind maps a declared kind onto a known one, or "" for an unknown one — refused rather than degraded, exactly as an action input's kind is: a control the host draws as the wrong type collects the wrong value and the plugin filters on it.
type FilterOption ¶
FilterOption is one option of a choice filter.
type GetParams ¶
type GetParams struct {
Collection string `json:"collection"`
ID string `json:"id"`
Filters map[string]string `json:"filters,omitempty"`
}
GetParams addresses one row of one collection.
Filters is the applied filter set of the list that produced the row, sent exactly as that list sent it. A row found under a filter-chosen scope has to expand under the same scope: sending nothing makes the plugin resolve the row under its declared defaults, which is at best a different document and at worst a refusal, because the row was only visible under the scope the user chose. Same shape and same rule as ListParams.Filters — a missing key means the filter's declared default, and the host drops undeclared keys before the call.
type GetRequest ¶
type GetRequest struct {
Instance string
Params GetParams
Context *Context
// Refresh bypasses cached freshness for this call and re-caches the
// result. A failed refresh leaves the last good document available.
Refresh bool
// PaneKey identifies the surface asking, exactly as it does for a list. A
// second get for the same key supersedes the first: the earlier call's
// context is cancelled, which kills its process group. That is what makes
// a detail box that follows the cursor affordable — ten rows cost at most
// one live process, not ten. Empty means "no pane", and nothing is
// superseded, which is what a CLI call wants.
PaneKey string
}
GetRequest addresses one get call.
type HostInfo ¶
HostInfo identifies Sidecar to a plugin. It carries no user, no project, no repository, and no environment.
type Info ¶
type Info struct {
Kind string `json:"kind,omitempty"`
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
// DocsURL is the only executable-declared Setup action Sidecar will
// follow, and only after user confirmation. It passes the same http/https
// validation as a resource's sourceUrl.
DocsURL string `json:"docsUrl,omitempty"`
}
Info is the informational identity a provider declares. None of it can rename or collide with a configured instance ID.
type InputKind ¶
type InputKind string
InputKind is the shape of one action input.
func CoerceInputKind ¶
CoerceInputKind maps a declared kind onto a known one, or "" for an unknown one — refused rather than degraded, because a form field the host draws as the wrong type collects the wrong value.
type Item ¶
type Item struct {
// ID is what get and item actions receive.
ID string
// Cells is keyed by column ID; a missing cell renders blank.
Cells map[string]string
// Status is an optional pill.
Status *resource.Status
// SourceURL is an optional validated http(s) URL.
SourceURL string
}
Item is one row of a page.
type ListParams ¶
type ListParams struct {
Collection string `json:"collection"`
Query string `json:"query"`
View string `json:"view"`
Sort SortOrder `json:"sort"`
Filters map[string]string `json:"filters,omitempty"`
Cursor string `json:"cursor"`
Limit int `json:"limit"`
}
ListParams addresses one page of one collection.
Filters carries every declared filter whose value is not its default; a missing key means the default. The host drops undeclared keys before the call, so a plugin only ever reads names it published itself.
type ListRequest ¶
type ListRequest struct {
Instance string
Params ListParams
// Context is what the caller can offer. The provider narrows it to the
// kinds the plugin declared, so offering more than a plugin reads is safe.
Context *Context
// PaneKey identifies the surface asking. A second list for the same pane
// supersedes the first: the earlier call's context is cancelled, which
// kills its process group. Empty means "no pane", and nothing is
// superseded — which is what a CLI call wants.
PaneKey string
}
ListRequest addresses one list call.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager is the host-owned, long-lived owner of provider process policy: it describes instances, publishes the matcher snapshot, caches successful resolves, deduplicates identical in-flight resolves, and bounds concurrency.
It is not a Sidecar plugin. It has no tab, no View, and no independent lifecycle; the app injects its read-only snapshot and its Resolve method into whichever surface needs them, so the project Workspace and the global Workspaces browser share one status, cache, and process policy.
func NewManager ¶
func NewManager(opts ManagerOptions) *Manager
NewManager builds a manager with no providers.
func (*Manager) Act ¶
Act performs one typed operation.
It is never cached and never deduplicated. Two identical acts are two intentions, and collapsing them into one would silently drop a change the user asked for twice on purpose.
func (*Manager) CancelPane ¶
CancelPane cancels whatever call is in flight for a pane — a list or a get — killing its process group. A pane that closes while a slow call is running must not leave a child behind.
func (*Manager) Collection ¶
func (m *Manager) Collection(instance, collection string) (Collection, bool)
Collection returns one declared collection of one instance.
func (*Manager) DescribeAll ¶
DescribeAll describes every enabled instance concurrently, publishes a new matcher snapshot from the results, and returns each instance's status.
It never runs on the first-frame path. The app starts it from a cancellable command that waits on the ready-frame latch.
func (*Manager) Description ¶
func (m *Manager) Description(instance string) (Description, bool)
Description returns an instance's newest validated describe result.
func (*Manager) Get ¶
Get expands one collection row into one document. It shares the resolve cache: a second Enter on the same row costs no process.
With a PaneKey it also supersedes: the surface's previous get is cancelled and its process group killed, on the same rule and through the same pending map List uses. A cursor moving down a list is one surface asking a new question, not ten surfaces asking at once.
func (*Manager) List ¶
List returns one page of one collection.
The collection must be one the instance declared in its newest successful describe. That is not ceremony: the declaration is what says which columns exist, and a page sanitized against no declaration would carry cells the host has nowhere to paint. It also means a list for a collection that has gone away fails with a typed error rather than starting a process to find out.
func (*Manager) Resolve ¶
func (m *Manager) Resolve(ctx context.Context, ref resource.Reference, refresh bool) (resource.Document, error)
Resolve turns a reference into a document. Successful results are cached and identical in-flight requests share one invocation.
refresh bypasses freshness for this call and re-caches the result. It does not drop the previous entry up front: a failed refresh must leave the last good document available to whoever still holds it.
func (*Manager) SetProviders ¶
SetProviders replaces the configured set, in configuration order — which is matcher precedence. disabled names instances that are configured but turned off; they keep a status and contribute no matchers.
An instance that disappears becomes StateRemoved rather than vanishing, so a diagnostic surface can still explain why a saved reference is not resolving.
func (*Manager) SnapshotError ¶
SnapshotError reports the most recent failed snapshot replacement.
type ManagerOptions ¶
type ManagerOptions struct {
MaxConcurrent int
MaxConcurrentPerProvider int
Log *slog.Logger
// Now is injectable for cache-expiry tests.
Now func() time.Time
}
ManagerOptions configure a Manager. The zero value is usable.
type Matcher ¶
type Matcher struct {
ID string `json:"id"`
Pattern string `json:"pattern"`
Priority int `json:"priority,omitempty"`
}
Matcher is one declared resource-key shape. The pattern is Go/RE2 and the whole match is the locator: there are no capture-group templates and no provider code runs in the scanner.
type Omitted ¶
Omitted is what the plugin held back from a page it could otherwise have filled: rows below its own relevance floor, and rows past its budget. The host renders both as data in the summary row rather than leaving a plugin to write them into free-text notices.
type OpenTarget ¶
OpenTarget is a row an action asks the host to open afterwards.
type Options ¶
type Options struct {
// Dir is the neutral working directory every child gets — a Sidecar config
// directory, never a selected repository.
Dir string
// HostEnv is the os.Environ()-shaped environment to draw the documented
// base from. Nil means the current process environment.
HostEnv []string
// Runner overrides the process adapter. Nil means ExecRunner.
Runner Runner
// Log receives metadata-only invocation records.
Log *slog.Logger
// Home bounds declared watch paths. Empty resolves from HostEnv and then
// from the OS.
Home string
}
Options carries the host context a set of plugins is built with. Everything in it is resolved before any child runs.
type Outcome ¶
type Outcome struct {
Status ActStatus
Message string
// Refresh names collections the host should re-list if they are visible.
Refresh []string
// Open is the capture-then-show row, or nil.
Open *OpenTarget
}
Outcome is one act answer.
func SanitizeOutcome ¶
func SanitizeOutcome(w *WireOutcome) Outcome
SanitizeOutcome enforces the act response's bounds. An outcome with no readable status is a failure, because an action whose result the host cannot read must never be reported to the user as having worked.
type Page ¶
type Page struct {
Outcome PageOutcome
Items []Item
// NextCursor is opaque; empty means no more. The host pages on demand,
// never eagerly.
NextCursor string
// Total is an optional count for the footer. Zero means the plugin did not
// say.
Total int
Notices []Notice
// Omitted is what the plugin held back, as counts the summary row renders
// as data.
Omitted Omitted
// Coverage is the per-source ledger, read only by the coverage modal.
Coverage []Coverage
// Truncated reports that the plugin sent more items than the host keeps.
Truncated bool
// CoverageTruncated reports the same for the coverage ledger, so the modal
// can say the table is not the whole of it rather than implying it is.
CoverageTruncated bool
}
Page is one list answer.
func SanitizePage ¶
func SanitizePage(w *WirePage, collection Collection) Page
SanitizePage enforces every page bound and returns rows safe to render.
It truncates rather than refusing, which is the same rule SanitizeDocument follows and for the same reason: a plugin is not required to pre-truncate to the host's numbers, the numbers are not sent in the request, and a page that is merely too big should still show the user their results. Items past the limit are dropped and the page is marked truncated; a cell longer than the bound is cut; a cell whose column the plugin never declared is dropped, because the host has nowhere to draw it.
The only refusal is structural, and it belongs to the caller: a row with no id cannot be opened or acted on, so it is dropped here rather than shown as a row that does nothing.
type PageOutcome ¶
type PageOutcome string
PageOutcome is what a list call is claiming about coverage.
const ( // OutcomeAnswered means the plugin asked everything it should have. OutcomeAnswered PageOutcome = "answered" // OutcomeAbstained means nothing matched and every source was fine, so an // empty list honestly reads as "no matches". OutcomeAbstained PageOutcome = "abstained" // OutcomeDegraded means some eligible source could not answer, so an empty // list reads as "no matches, and coverage was incomplete". OutcomeDegraded PageOutcome = "degraded" // OutcomeFailed means every source that was asked failed, so the page says // nothing at all about the query. The host renders an error card over an // empty list and never the words "no matches", which would be a claim // nothing made. OutcomeFailed PageOutcome = "failed" )
func CoercePageOutcome ¶
func CoercePageOutcome(v string) PageOutcome
CoercePageOutcome maps a declared outcome onto a known one.
An absent outcome is "answered": that is what every plugin that never thinks about coverage means. An outcome this version does not recognise becomes degraded rather than answered, because the honest reading of a claim the host cannot understand is that coverage is unknown — and of the two ways to be wrong, saying "coverage may be incomplete" is the one that does not invent a guarantee on the plugin's behalf.
type PluginProvider ¶
type PluginProvider interface {
Provider
// List returns one page of one collection. collection is the validated
// declaration from the describe snapshot, which is how the host knows
// which cells a row is allowed to carry.
List(ctx context.Context, params ListParams, callCtx *Context, collection Collection) (Page, error)
// Get expands one row into one document, with sections. collection is the
// validated declaration, which is how the host narrows the applied filters
// the row was found under before they reach the plugin.
Get(ctx context.Context, params GetParams, callCtx *Context, collection Collection) (resource.Document, error)
// Act performs one typed operation. It is the only method that mutates.
Act(ctx context.Context, params ActParams, callCtx *Context) (Outcome, error)
}
PluginProvider is a Provider that also speaks the plugin protocol. It is a separate interface rather than three more methods on Provider so that a resource provider — and every in-memory fake written against the frozen protocol — stays a complete implementation of what it actually offers.
All three methods must be safe for concurrent use and must honor ctx.
type ProjectContext ¶
type ProjectContext struct {
Root string `json:"root,omitempty"`
WorkDir string `json:"workDir,omitempty"`
Name string `json:"name,omitempty"`
Branch string `json:"branch,omitempty"`
HostID string `json:"hostId,omitempty"`
}
ProjectContext describes the surface's project. On a remote-bound surface HostID is non-empty and the paths are that machine's, so a plugin that only knows this machine can say so with a typed unavailable naming the host rather than answering about the wrong checkout.
type Provider ¶
type Provider interface {
// Instance is the configured provider instance ID. It is host-owned: a
// provider cannot rename itself, and a response never changes it.
Instance() string
// Describe reports what the provider is and what it can recognize. It must
// be local, fast, and non-interactive: no credential prompt, no network.
Describe(ctx context.Context) (Description, error)
// Resolve turns one locator into one document. It may perform network I/O.
Resolve(ctx context.Context, ref resource.Reference) (resource.Document, error)
}
Provider is the whole of what the Manager may ask an implementation to do. Both methods must be safe for concurrent use and must honor ctx.
func FromConfig ¶
FromConfig builds one CommandProvider per enabled terminal resource provider, in configuration order — which is matcher precedence — and returns the IDs of the instances that are configured but disabled.
It performs no I/O: it does not look up the command on PATH, does not stat anything, and does not start a process. That is what makes it safe to call from a command after the first frame without having done anything before it.
func FromInstances ¶
FromInstances builds one CommandProvider per enabled instance of the merged list, in order, and returns the IDs of the ones that are configured but off.
The protocol identifier each instance is dispatched with comes from the section it was configured in, never from anything the executable says. That is the whole of how the two dialects coexist: a plugin cannot upgrade itself by answering with a different string, and a resource provider whose entry was never moved keeps being asked exactly what it has always been asked.
It performs no I/O for the same reason FromConfig does not.
type Refresh ¶
type Refresh struct {
// EverySeconds is a poll interval, clamped to [15, 900] and polled only
// while a tab from this plugin is visible. Zero means no polling.
EverySeconds int
// Watch are absolute paths under the user's home directory, already
// expanded and validated. A change to one re-lists visible collections.
Watch []string
}
Refresh is how a collection stays current without a resident process.
type Request ¶
type Request struct {
Protocol string `json:"protocol"`
Method string `json:"method"`
Instance string `json:"instance"`
DeadlineMs int64 `json:"deadlineMs"`
Host *HostInfo `json:"host,omitempty"`
// Context is present only for kinds the plugin declared in describe and
// the host actually has. An undeclared kind is never sent.
Context *Context `json:"context,omitempty"`
Params any `json:"params,omitempty"`
}
Request is the single JSON object written to a plugin's stdin.
DeadlineMs is advisory but accurate: it is exactly the timeout the host is about to enforce. A plugin that budgets its own I/O inside it can return a typed `unavailable` — which gives the user a real error card and a working Retry — instead of being SIGKILLed, which gives them an opaque transport failure.
Params is typed per method (*ResolveParams, *ListParams, *GetParams, *ActParams) rather than one union struct, because a union would encode every method's fields on every call and a plugin author reading the wire would have to guess which of them applied.
type ResolveParams ¶
ResolveParams is the whole of what a resolve request carries. Widening it requires a named capability and an explicit per-instance permission, not a silent field addition.
type Response ¶
type Response struct {
Protocol string `json:"protocol"`
// Plugin is the plugin protocol's spelling of the identity block; Provider
// is the resource protocol's. Both are accepted on both dialects — an
// author who copied a resource provider's response is describing the same
// thing under the older name — and Plugin wins when both are present.
Plugin *Info `json:"plugin,omitempty"`
Provider *Info `json:"provider,omitempty"`
Context []string `json:"context,omitempty"`
Matchers []Matcher `json:"matchers,omitempty"`
Collections []WireCollection `json:"collections,omitempty"`
Actions []WireAction `json:"actions,omitempty"`
Resource *resource.WireDocument `json:"resource,omitempty"`
Page *WirePage `json:"page,omitempty"`
Outcome *WireOutcome `json:"outcome,omitempty"`
Error *resource.WireError `json:"error,omitempty"`
}
Response is the single JSON object read from a plugin's stdout. Exactly one of the describe shape, Resource, Page, Outcome, or Error is meaningful.
type RunResult ¶
type RunResult struct {
Stdout []byte
StdoutBytes int
StdoutTruncated bool
StderrBytes int
ExitCode int
Duration time.Duration
// TimedOut reports that the process group was killed because ctx expired
// or was canceled, rather than the child exiting on its own.
TimedOut bool
}
RunResult is what an invocation produced. Stderr content is never present: only its byte count, which is all the protocol allows Sidecar to keep.
type RunSpec ¶
type RunSpec struct {
// Argv is executed directly. No shell, ever. Argv[0] may be an absolute
// path or resolve through PATH.
Argv []string
// Dir is a neutral Sidecar config directory, never a selected repository.
Dir string
// Env is the complete environment. Nothing is inherited implicitly.
Env []string
// Stdin is written once and then closed.
Stdin []byte
// MaxStdout bounds what is retained from stdout. The stream keeps being
// drained past the bound so the child cannot block on a full pipe; the
// excess is counted and discarded.
//
// There is no stderr equivalent, and that is the contract, not an
// omission: stderr is never retained at all, and stopping its drain at a
// byte bound would deadlock a chatty provider against a full pipe.
MaxStdout int
}
RunSpec is one invocation of a provider executable. It is deliberately a value with no callbacks: everything the child sees is decided before it starts, and nothing about the host leaks in.
type Runner ¶
Runner is the process adapter. The default implementation spawns a real child; tests substitute a fake to exercise the protocol layer without a process, and the executable fixture tests exercise the real one.
type SearchMode ¶
type SearchMode string
SearchMode is whether a collection takes a query.
const ( // SearchNone means the collection has no query line. SearchNone SearchMode = "none" // SearchOptional means a query filters the collection. SearchOptional SearchMode = "optional" // SearchRequired means the collection is empty until there is a query. The // host answers an empty query itself, without starting a process. SearchRequired SearchMode = "required" )
func CoerceSearchMode ¶
func CoerceSearchMode(v string) SearchMode
CoerceSearchMode maps a declared value onto a known one. An unknown value becomes SearchNone rather than SearchRequired: a collection the host cannot classify must still be listable.
type SelectionContext ¶
type SelectionContext struct {
Text string `json:"text"`
}
SelectionContext is the selected text an action was invoked over.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is an immutable, ordered set of compiled matchers. The scanner holds one for the duration of a scan; a replacement never mutates one in place.
It also carries each instance's claimed hosts, keyed by instance ID. Claims ride on the same snapshot as the matchers so that a claimed URL can only be reclassified by a matcher that is live in exactly this generation — and so that a refused replacement keeps claims and matchers consistent with each other.
func (*Snapshot) ClaimHosts ¶
ClaimHosts reports an instance's claimed hostnames in their normalized, lowercase form. Unknown instances return nil.
func (*Snapshot) Generation ¶
Generation identifies this snapshot. Cache entries and in-flight resolves are scoped to it, so a re-describe cannot serve a document keyed by a matcher set that no longer exists.
func (*Snapshot) Lookup ¶
func (s *Snapshot) Lookup(instance, id string) (CompiledMatcher, bool)
Lookup finds a matcher by instance and ID.
func (*Snapshot) Matchers ¶
func (s *Snapshot) Matchers() []CompiledMatcher
Matchers returns the ordered matchers. The slice is a copy; the compiled expressions inside it are shared and safe for concurrent use.
func (*Snapshot) TerminalMatchers ¶
func (s *Snapshot) TerminalMatchers() []terminallink.ResourceMatcher
TerminalMatchers adapts the snapshot into the scanner's vocabulary, already in precedence order. It is the only crossing between provider machinery and the scanner: terminallink learns a pattern and a reference, never a process, a document, or this package.
Each matcher carries its instance's claimed hosts. That is how the URL-yield rule reaches the scanner without widening this crossing: the scanner sees a host list on the same value that already named the pattern and the reference, and it can only reclassify a built-in URL span when one of those hosts matches AND this matcher matches the entire URL.
type SnapshotStore ¶
type SnapshotStore struct {
// contains filtered or unexported fields
}
SnapshotStore holds the current snapshot and swaps it atomically.
A failed replacement keeps the previous snapshot for the remainder of the process and reports the new failure. That is deliberate: dropping working matchers because a later describe went wrong would turn a provider hiccup into terminal output silently losing links, and relaunch already starts clean.
func NewSnapshotStore ¶
func NewSnapshotStore() *SnapshotStore
NewSnapshotStore returns a store holding an empty snapshot.
func (*SnapshotStore) Current ¶
func (s *SnapshotStore) Current() *Snapshot
Current returns the live snapshot. It never returns nil.
func (*SnapshotStore) LastError ¶
func (s *SnapshotStore) LastError() error
LastError reports the most recent failed replacement, or nil if the last replacement succeeded.
func (*SnapshotStore) Replace ¶
func (s *SnapshotStore) Replace(sets []DescribedSet) error
Replace compiles every declared matcher and publishes a new snapshot. On any failure the previous snapshot stays live and the error is recorded.
type SortDir ¶
type SortDir string
SortDir is a sort direction.
func CoerceSortDir ¶
CoerceSortDir maps a declared direction onto a known one, with "" preserved as "the plugin stated no default".
type SortKey ¶
type SortKey struct {
ID string
Label string
// Default is "asc"/"desc" when this key is the collection's default sort,
// and "" otherwise.
Default SortDir
}
SortKey is one sortable key offered in the sort picker.
type SortOrder ¶
SortOrder is the chosen sort key and direction, both empty when the plugin declared no sort keys.
type State ¶
type State string
State is a provider instance's readiness. It is explicit rather than inferred, because "describe has not returned yet" and "this matcher was deleted" must never be the same value: restore has to be able to keep an armed resource tab through the first, and only the user's own close removes one.
const ( // StateUnchecked is the starting state: configured, never described. StateUnchecked State = "unchecked" // StateReady means the last describe succeeded and its matchers are live. StateReady State = "ready" // StateTemporarilyFailed means describe failed in a way a retry might fix. StateTemporarilyFailed State = "temporarily-failed" // StateIncompatible means the provider answered but does not speak this // protocol version, or its describe result cannot be published. StateIncompatible State = "incompatible" // StateDisabled means configuration turned this instance off. StateDisabled State = "disabled" // StateRemoved means the instance is no longer in configuration. Armed // references to it are preserved, not pruned. StateRemoved State = "removed" )
type Status ¶
type Status struct {
Instance string
State State
Info Info
MatcherCount int
LastChecked time.Time
// LastError is the typed error of the last failed describe, or nil.
LastError *resource.Error
// LastOutcome is the single-token outcome of the last describe.
LastOutcome string
Duration time.Duration
// Command is the configured argv of a command-backed provider, and
// CommandPath the file argv[0] resolved to, recorded when the last describe
// failed.
//
// Both are empty after a successful describe and for a provider that runs
// no process. Recording them only on failure is the point: a bare command
// name resolves against whatever PATH Sidecar was started with, so "which
// file did it actually run" is the answer to most describe failures and a
// PATH lookup nobody needs when the plugin works.
Command []string
CommandPath string
}
Status is one instance's diagnostic state. It carries no locator, no document, and no provider output.
type TransportError ¶
type TransportError struct {
Instance string
Method string
Reason TransportReason
Detail string
Err error
}
TransportError is a failure of the process boundary rather than of the service. It deliberately carries no stdout, no stderr, and no locator: the Detail is host-authored text, so logging or rendering it cannot leak provider output.
func (*TransportError) Error ¶
func (e *TransportError) Error() string
func (*TransportError) ResourceError ¶
func (e *TransportError) ResourceError() *resource.Error
ResourceError maps a transport failure onto the typed code a card shows.
The mapping is deliberate: `unavailable` means "the thing on the other end did not answer in time", which is what a timeout is from the user's side; `invalid_config` means "this instance is not set up", which is what an unstartable command is; everything else is the provider misbehaving, which is `internal` and retryable because a retry is free and sometimes works.
The three reasons that a wrong executable produces — it would not start, it exited without answering, it wrote something that is not a response — each say so in their own words rather than sharing one. A bare command name is resolved against whatever PATH Sidecar was started with, so the commonest cause of all three is a second, older build of the right tool winning the lookup, and a message that blames the protocol sends the user to read the wrong thing. Each carries the hint that prints the file actually run.
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
type TransportReason ¶
type TransportReason string
TransportReason names the ways an invocation can fail without the provider ever having told Sidecar anything typed. Every one of them is attributed to the provider, never to the service it talks to.
const ( // ReasonSpawn is a command that could not be started at all: not on PATH, // not executable, no such directory. ReasonSpawn TransportReason = "spawn" // ReasonExit is a non-zero exit status. ReasonExit TransportReason = "exit" // ReasonTimeout is exceeding the configured timeout. ReasonTimeout TransportReason = "timeout" // ReasonCanceled is the caller withdrawing the request. ReasonCanceled TransportReason = "canceled" // ReasonMalformed is no JSON or unparseable JSON on stdout. ReasonMalformed TransportReason = "malformed" // ReasonExtraOutput is more than one top-level JSON value on stdout. ReasonExtraOutput TransportReason = "extra-output" // ReasonOversize is stdout past the response byte limit. ReasonOversize TransportReason = "oversize" // ReasonProtocol is a missing or mismatched protocol field. ReasonProtocol TransportReason = "protocol" // ReasonInvalidDescribe is a describe result that failed host validation: // an uncompilable pattern, a duplicate matcher ID, a bound exceeded. ReasonInvalidDescribe TransportReason = "invalid-describe" // ReasonInvalidRequest is a request the host refused to send. ReasonInvalidRequest TransportReason = "invalid-request" // ReasonShape is a response that is not exactly one of the three permitted // shapes: a describe result, a resource result, or a typed error. ReasonShape TransportReason = "shape" // ReasonInvalidResource is a resource object the host cannot render and // cannot truncate its way out of — one with no identity or no title. ReasonInvalidResource TransportReason = "invalid-resource" )
type WireAction ¶
type WireAction struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
On string `json:"on,omitempty"`
Collection string `json:"collection,omitempty"`
Inputs []WireActionInput `json:"inputs,omitempty"`
Mutates bool `json:"mutates,omitempty"`
Confirm *bool `json:"confirm,omitempty"`
Key string `json:"key,omitempty"`
}
WireAction is one `actions[]` element. Confirm is a pointer because the default depends on the action: a mutating action with no inputs confirms unless the plugin explicitly said not to.
type WireActionInput ¶
type WireActionInput struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
Kind string `json:"kind,omitempty"`
Required bool `json:"required,omitempty"`
Choices []string `json:"choices,omitempty"`
Default string `json:"default,omitempty"`
}
WireActionInput is one `inputs[]` element of an action.
type WireCollection ¶
type WireCollection struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
Search string `json:"search,omitempty"`
Columns []WireColumn `json:"columns,omitempty"`
Views []WireView `json:"views,omitempty"`
Sort []WireSortKey `json:"sort,omitempty"`
Filters []WireFilter `json:"filters,omitempty"`
Detail *bool `json:"detail,omitempty"`
Refresh *WireRefresh `json:"refresh,omitempty"`
Context []string `json:"context,omitempty"`
}
WireCollection is one `collections[]` element of a describe result. Detail is a pointer because a collection that says nothing about it means "rows can be opened", which is the useful default, and an omitted false would silently disable Enter.
type WireColumn ¶
type WireColumn struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
Width int `json:"width,omitempty"`
Align string `json:"align,omitempty"`
Kind string `json:"kind,omitempty"`
Primary bool `json:"primary,omitempty"`
Secondary bool `json:"secondary,omitempty"`
}
WireColumn is one `columns[]` element of a collection.
type WireCoverage ¶
type WireCoverage struct {
Source string `json:"source"`
State string `json:"state,omitempty"`
Reason string `json:"reason,omitempty"`
ElapsedMs int `json:"elapsedMs,omitempty"`
}
WireCoverage is one `page.coverage[]` element.
type WireFilter ¶
type WireFilter struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
Kind string `json:"kind,omitempty"`
Choices []WireFilterChoice `json:"choices,omitempty"`
Default string `json:"default,omitempty"`
}
WireFilter is one `filters[]` element of a collection.
type WireFilterChoice ¶
WireFilterChoice is one `choices[]` element of a choice filter.
type WireItem ¶
type WireItem struct {
ID string `json:"id"`
Cells map[string]string `json:"cells,omitempty"`
Status *resource.WireStatus `json:"status,omitempty"`
SourceURL string `json:"sourceUrl,omitempty"`
}
WireItem is one `page.items[]` element.
type WireNotice ¶
WireNotice is one `page.notices[]` element.
type WireOmitted ¶
type WireOmitted struct {
Suppressed int `json:"suppressed,omitempty"`
Dropped int `json:"dropped,omitempty"`
}
WireOmitted is the `page.omitted` object: what the plugin held back.
type WireOpen ¶
type WireOpen struct {
Collection string `json:"collection,omitempty"`
ID string `json:"id,omitempty"`
}
WireOpen is the `outcome.open` object.
type WireOutcome ¶
type WireOutcome struct {
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Refresh []string `json:"refresh,omitempty"`
Open *WireOpen `json:"open,omitempty"`
}
WireOutcome is the `outcome` object of an act response.
type WirePage ¶
type WirePage struct {
Outcome string `json:"outcome,omitempty"`
Items []WireItem `json:"items,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
Total int `json:"total,omitempty"`
Notices []WireNotice `json:"notices,omitempty"`
Omitted *WireOmitted `json:"omitted,omitempty"`
Coverage []WireCoverage `json:"coverage,omitempty"`
}
WirePage is the `page` object of a list response.
type WireRefresh ¶
type WireRefresh struct {
EverySeconds int `json:"everySeconds,omitempty"`
Watch []string `json:"watch,omitempty"`
}
WireRefresh is a collection's `refresh` object.
type WireSortKey ¶
type WireSortKey struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
Default string `json:"default,omitempty"`
}
WireSortKey is one `sort[]` element.