plugin

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 20 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 plugin defines the portable contract for independently provided capabilities. Consumers own domain semantics, authorization, installation locations, and native behavior. A descriptor is a declaration, not a grant.

Index

Constants

View Source
const (
	// BoundaryInProcess shares the host's address space and authority.
	BoundaryInProcess = "in-process"
	// BoundaryProcess is a separate process with the user's full authority.
	BoundaryProcess = "process"
	// BoundaryConfined is a separate process restricted by OS policy.
	BoundaryConfined = "confined"
	// BoundaryRuntime has no syscall ABI, only the imports the host supplies.
	BoundaryRuntime = "runtime"
	// BoundaryContainer is a process in namespaces managed by a container runtime.
	BoundaryContainer = "container"
	// BoundaryKernel has its syscalls served by a separate kernel.
	BoundaryKernel = "kernel"
)

The sandbox boundary levels of docs/adr-sandboxing.md: where isolation is enforced for a guest. They are the same strings as src/cto/sandbox's levels; the engine does not import that module, so it keeps its own copy.

View Source
const (
	FrameReverseRequest  = "reverse_request"
	FrameReverseResponse = "reverse_response"
	FrameProgress        = "progress"
)

Frame values for the tagged frames that share a connection with requests and responses. A frame with no "frame" field is a request or response as before.

View Source
const (
	// ReverseUndeclared: the plugin's descriptor does not list the operation in
	// Reverse. Fix the descriptor.
	ReverseUndeclared = "reverse_undeclared"
	// ReverseUnavailable: the host offers no reverse services, or not yet.
	ReverseUnavailable = "reverse_unavailable"
	// ReverseDenied: the host's Authorize refused this call.
	ReverseDenied   = "denied"
	ReverseTooLarge = "too_large"
	ReverseBusy     = "busy"
	ReverseExpired  = "expired"
)

Stable codes of the errors a reverse call fails with. They let a guest tell a feature that is not offered (fall back) from one that is forbidden, and debug a missing declaration.

View Source
const (
	DefaultReversePayloadBytes = 1 << 20
	DefaultReverseInFlight     = 4
	MaxProgressTextBytes       = 2048
)

Bounds and defaults for reverse calls and progress.

View Source
const APIVersion = "ext.io.pc/v1"
View Source
const AdapterAPIVersion = "2.0"

AdapterAPIVersion is the version of Ext's adapter process protocol.

View Source
const AdapterContractName = "ext.adapter"

AdapterContractName identifies Ext's argv/stream adapter binding. Its version is the adapter API, independently of the plugin envelope API.

View Source
const DefaultProgressBytes = 64 << 10
View Source
const DefaultProgressEvents = 50
View Source
const DefaultTimeout = 30 * time.Second
View Source
const MaxFrameBytes = 24 << 20
View Source
const MaxRetryAfterMilliseconds int64 = 365 * 24 * 60 * 60 * 1000

MaxRetryAfterMilliseconds bounds a RemoteError retry hint to one year.

Variables

View Source
var (
	ErrInvalid     = errors.New("invalid plugin contract")
	ErrUnsupported = errors.New("unsupported plugin operation")
	ErrNotFound    = errors.New("no matching plugin")
	ErrAmbiguous   = errors.New("multiple matching plugins")
	ErrDenied      = errors.New("plugin admission denied")
	ErrMismatch    = errors.New("plugin identity or contract mismatch")
	ErrClosed      = errors.New("plugin session closed")
	ErrDraining    = errors.New("plugin session draining")
)
View Source
var (
	// ErrProgressDropped tells a reporter that its event was dropped by the
	// rate limit. It is informational: the call continues, and the next
	// delivered event carries the count.
	ErrProgressDropped = errors.New("plugin progress event dropped")
	// ErrProtocol marks a peer violating the framing rules. A session that
	// sees one fails and is not reusable.
	ErrProtocol = errors.New("plugin protocol violation")
)

Boundaries lists every boundary level.

Functions

func ArtifactDigest

func ArtifactDigest(root, relative string, tree bool) (string, error)

ArtifactDigest returns the digest of one artifact under root, addressed by a portable relative path, never following symbolic links: the SHA-256 of a file, or for a tree the directory digest of a directory that holds at least one file. A symbolic link at any component, a path that is not portable and a final component of the wrong kind are ErrInvalid.

func CheckRequirements

func CheckRequirements(d Descriptor, requirements []Requirement) error

CheckRequirements is a preflight for exact domain operations, including optional SDK capabilities. Call before launch; Open still verifies and checks the complete descriptor. A preflight is never an admission decision.

func Decode

func Decode(data []byte, target any) error

Decode reads one bounded JSON value and rejects unknown fields and duplicate object keys (including in payloads), keeping admission and dispatch unambiguous.

func DirectoryDigest

func DirectoryDigest(root string) (string, error)

DirectoryDigest hashes every regular file, including manifests and assets, in sorted slash-path order. Symlinks and special files are rejected. The digest format preserves CTX's existing adapter trust records: SHA256(concat("./" + relativePath + " " + fileSHA256 + "\n")). Installers must protect the directory against concurrent replacement; this function is integrity checking, not an OS sandbox or atomic exec primitive.

func MatchHandshake

func MatchHandshake(selected, actual Descriptor) error

MatchHandshake rejects both expansion and reduction of the selected contract. Declaration ordering is insignificant.

func Method

func Method(ref ContractRef, operation string) string

Method is the inverse of ResolveMethod: "<contract name>.<operation>".

func NegotiateProtocol

func NegotiateProtocol(preferred, offered []string) (string, error)

NegotiateProtocol selects the first locally preferred exact protocol offered by a peer. Offers must come from reviewed metadata or an authenticated native bootstrap. This does not authenticate a peer or change the v1 hello format. Only pass versions for which the caller has an installed implementation.

func PortablePath

func PortablePath(value string) bool

PortablePath reports whether value is a portable relative path: slash separated, with no empty, "." or ".." component, no backslash, colon, NUL or line break, no component ending in "." or a space, no Windows device name, and at most 1024 bytes. Package artifact paths must satisfy it.

func SplitProgressText

func SplitProgressText(text string) []string

SplitProgressText cuts text into pieces that each fit one event: at most MaxProgressTextBytes bytes and valid UTF-8. A piece never ends inside a multi-byte character, and bytes that are not valid UTF-8 are replaced with U+FFFD, because an event carrying either is a protocol violation. Splitting a longer line into events, and where, is the reporter's job; this only keeps each piece legal. It returns nil for empty text.

func TreeDigest

func TreeDigest(root, dir string) (string, error)

TreeDigest returns DirectoryDigest of the directory dir (a slash-separated portable path) under root, for a tree artifact. Every component of dir must be a plain directory, and the directory must hold at least one file and only regular files and directories.

func ValidBoundary

func ValidBoundary(b string) bool

ValidBoundary reports whether b is one of the boundary levels.

func ValidIdentifier

func ValidIdentifier(s string) bool

ValidIdentifier checks a protocol identifier.

func ValidRevision

func ValidRevision(s string) bool

ValidRevision checks a protocol revision or request identifier.

func ValidateRequest

func ValidateRequest(d Descriptor, r Request) error

ValidateRequest enforces the selected descriptor, before domain admission. Payload semantics and any authorization references are consumer-owned.

func WithProgressLimits

func WithProgressLimits(ctx context.Context, limits *ProgressLimits) context.Context

WithProgressLimits attaches the resolved event rate of the call being handled; pass nil for a call that has none.

func WithProgressReporter

func WithProgressReporter(ctx context.Context, r ProgressReporter) context.Context

WithProgressReporter attaches the reporter for the call being handled.

func WithProgressSink

func WithProgressSink(ctx context.Context, s ProgressSink) context.Context

WithProgressSink attaches the sink for the call being made.

func WithReverse

func WithReverse(ctx context.Context, c ReverseCaller) context.Context

WithReverse attaches the caller for the call in flight; ReverseFrom reads it.

func WithSessionReverse

func WithSessionReverse(ctx context.Context, c ReverseCaller) context.Context

WithSessionReverse attaches the caller for session-scoped reverse calls.

Types

type AdapterInvocation

type AdapterInvocation struct {
	Operation   string
	Selection   string
	Arguments   []string
	API         string
	Name        string
	Command     string
	RealCommand string
	Project     string
	Profile     string
	Values      map[string]string
}

AdapterInvocation is one operation delivered by an Ext host to an adapter executable.

func ParseAdapterInvocation

func ParseAdapterInvocation(args []string) (AdapterInvocation, error)

ParseAdapterInvocation reads the versioned ext adapter process invocation. Call it with os.Args[1:]. It also accepts direct invocations without the legacy EXT_* environment variables, which makes an adapter executable easy to inspect during development.

type Backend

type Backend interface {
	Endpoint
	Close() error
}

Backend is a consumer-selected transport binding. Implementations must honor cancellation, permit concurrent Invoke calls (possibly serialized internally), and make Close interrupt transport I/O. In-host native execution has no forced termination: native Go handlers cooperate with contexts; C ABI cancellation releases the caller while native work and cleanup may remain outstanding. Backends never decide product authorization. A CLI binding may preserve raw streams outside this JSON invocation API and use ValidateRequest directly.

type BackendProfile

type BackendProfile struct {
	Name            string   `json:"name"`
	Protocols       []string `json:"protocols"`
	Concurrent      bool     `json:"concurrent"`
	Cancellation    string   `json:"cancellation"`
	ProcessOwner    string   `json:"processOwner"`
	NativeStreaming bool     `json:"nativeStreaming"`
	NativeCallbacks bool     `json:"nativeCallbacks"`
	Boundary        string   `json:"boundary,omitempty"`
}

BackendProfile describes transport mechanics, separately from the guest's domain contracts. Profiles are supplied by the selected backend factory. Boundary states where a guest on this backend is isolated, honestly: a backend that runs its guest in the host's process says in-process however it is wrapped. It is empty when the backend does not say. A profile never grants permissions; a boundary is a fact about the backend, not a policy.

func JSONLineProfile

func JSONLineProfile() BackendProfile

JSONLineProfile describes the standard JSON-line transport. It starts no guest.

type CallOptions

type CallOptions struct {
	// Progress sets the event rate for the call; zero fields use the defaults.
	Progress ProgressLimits
}

CallOptions tunes one CallProgress.

type Contract

type Contract struct {
	ContractRef
	Operations []Operation `json:"operations"`
}

type ContractRef

type ContractRef struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

func (ContractRef) Validate

func (ref ContractRef) Validate() error

type Descriptor

type Descriptor struct {
	APIVersion string     `json:"apiVersion"`
	Identity   Identity   `json:"identity"`
	Contracts  []Contract `json:"contracts"`
	// Reverse lists the host contracts and operations this plugin may call
	// while one of its own calls is in flight. A reverse call to anything not
	// listed is denied. Absent means the plugin makes no reverse calls.
	Reverse []Contract `json:"reverse,omitempty"`
}

func AdapterDescriptor

func AdapterDescriptor(identity Identity, operations []string) Descriptor

AdapterDescriptor translates a reviewed adapter package into the common contract. The caller supplies a content revision and declared operations. CLI adapters retain their argv, environment, exit status, and streams; this descriptor does not claim that they serve JSON-line plugin handshakes.

func Select

func Select(candidates []Descriptor, want Requirement) (Descriptor, error)

Select rejects ambiguity rather than applying an implicit provider preference. All candidates are validated; invalid discovery data is never silently used.

func (Descriptor) Clone

func (d Descriptor) Clone() Descriptor

func (Descriptor) Lookup

func (d Descriptor) Lookup(ref ContractRef, name string) (Operation, error)

Lookup uses exact contract versions. Consumers resolve release ranges and preference policy before handing an immutable selection to the host.

func (Descriptor) LookupReverse

func (d Descriptor) LookupReverse(ref ContractRef, name string) (Operation, error)

LookupReverse finds an operation the plugin declared it may call on the host.

func (Descriptor) ResolveMethod

func (d Descriptor) ResolveMethod(method string) (ContractRef, string, error)

ResolveMethod maps a dotted method name onto one declared contract and operation, for hosts and guests that address operations as a single string "<contract name>.<operation>". Contract names may themselves contain dots.

The longest declared contract name that prefixes the method wins, and the rest is the operation. When none does, the first dot-separated segment is tried: if exactly one declared contract name starts with that segment plus ".", that contract is used and everything after the segment is the operation. Otherwise the method is unresolved.

The result names a contract only. Whether the operation exists, and its surface, are still checked by Lookup and by the session at call time.

func (Descriptor) Validate

func (d Descriptor) Validate() error

type Endpoint

type Endpoint interface {
	Handshake(context.Context) (Descriptor, error)
	Invoke(context.Context, Request) (Response, error)
}

Endpoint is the shared host/guest interface. Transport clients implement it for hosts; Guest implements it for plugin authors. The interface carries no transport or process ownership. Backend adds host-side connection cleanup.

type Event

type Event struct {
	Stage     string
	Identity  Identity
	Contract  ContractRef
	Operation string
	RequestID string
	Duration  time.Duration
	Code      string
}

Event contains bounded metadata, never request/response payloads or error messages. Observers can derive logs, counters, latency histograms and spans.

type Guest

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

Guest holds an immutable declaration and a domain handler, reusable across in-process, JSON-line, RPC, native Go, WASI and C ABI backends. Each backend owns its connections; shutting one connection does not shut down the guest process.

func NewGuest

func NewGuest(descriptor Descriptor, opts GuestOptions) (*Guest, error)

func (*Guest) Handshake

func (g *Guest) Handshake(ctx context.Context) (Descriptor, error)

func (*Guest) Invoke

func (g *Guest) Invoke(ctx context.Context, request Request) (Response, error)

type GuestOptions

type GuestOptions struct {
	Handler Handler
	// MaxCallDuration is a guest-owned bound, independently of host deadlines.
	// Zero defaults to DefaultTimeout.
	MaxCallDuration time.Duration
}

type Handler

type Handler func(context.Context, Request) (json.RawMessage, error)

Handler authorizes and executes a consumer-owned operation. Implementations must check domain authority, honor ctx, and support concurrent calls when used with concurrent transports. Return RemoteError only for intentional public failures; other errors are reduced to generic diagnostic text.

type Identity

type Identity struct {
	ID       string `json:"id"`
	Revision string `json:"revision"`
	Version  string `json:"version,omitempty"`
}

Identity pins one immutable package selection. Revision changes whenever selected content or configuration changes, even at the same release Version. Version is optional release metadata; contract versions are independent.

func (Identity) Validate

func (id Identity) Validate() error

type Limiter

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

Limiter rate-limits events for one call and counts what it drops. It is safe for concurrent use.

func NewLimiter

func NewLimiter(l ProgressLimits, now func() time.Time) *Limiter

NewLimiter returns a limiter for the limits. now may be nil.

func (*Limiter) Admit

func (l *Limiter) Admit(p Progress) (dropped uint64, ok bool)

Admit reports whether the event may pass. When it passes, the returned count is the number of events dropped since the previous passing one, which the caller attaches to the event. When it does not, the drop is counted.

func (*Limiter) Carry

func (l *Limiter) Carry(n uint64)

Carry adds drops that a peer already counted, so they are reported in the next event instead of being lost with an event this limiter drops.

func (*Limiter) Pending

func (l *Limiter) Pending() uint64

Pending returns the drops not yet reported and resets the count.

type Observer

type Observer func(context.Context, Event)

Observer is synchronous and must be fast, concurrency-safe and nonblocking. ctx permits integration with the host's own tracing system. Observers must not panic. No global logger, exporter, payload capture or telemetry is used.

type Operation

type Operation struct {
	Name    string `json:"name"`
	Surface string `json:"surface,omitempty"`
	// Progress declares that a call to this operation may emit progress and log
	// frames before its response. Absent means it never does.
	Progress bool `json:"progress,omitempty"`
}

Operation names and surfaces belong to the consumer. Surface is an optional admission classification; it has no built-in vocabulary or authority.

type Options

type Options struct {
	// Verify must check the reviewed package selection before Connect may run.
	// A digest proves content equality, not publisher trust or permission.
	Verify  func(context.Context, Descriptor) error
	Connect func(context.Context, Descriptor) (Backend, error)
	// Authorize is required, called on every invocation, and receives copies.
	Authorize func(context.Context, Request) error
	// Timeout bounds handshake and calls without an earlier caller deadline.
	Timeout time.Duration
	// Observer receives metadata for admission and completed calls.
	Observer Observer
	// Requirements are checked before verification or connection.
	Requirements []Requirement
	// Reverse, when set, offers services to the plugin: calls from the plugin to
	// the host, limited to what its descriptor declares in Reverse. Without it
	// every reverse call is denied.
	Reverse *ReverseOptions
}

type Progress

type Progress struct {
	// Kind is "progress" or "log".
	Kind string `json:"kind"`
	// Stream is "", "out" or "err" and tells a program's standard streams apart
	// for log events.
	Stream    string `json:"stream,omitempty"`
	Text      string `json:"text,omitempty"`
	Completed uint64 `json:"completed,omitempty"`
	Total     uint64 `json:"total,omitempty"`
	// Dropped counts events lost to the rate limit since the previous delivered
	// event.
	Dropped uint64 `json:"dropped,omitempty"`
}

Progress is one progress or log event of a call.

func (Progress) Validate

func (p Progress) Validate() error

Validate checks an event's shape.

type ProgressFrame

type ProgressFrame struct {
	Frame      string `json:"frame"`
	APIVersion string `json:"apiVersion"`
	Parent     string `json:"parent"`
	Progress
}

ProgressFrame carries one event of the call named by Parent.

func (ProgressFrame) Validate

func (f ProgressFrame) Validate() error

Validate checks the frame's shape.

type ProgressLimits

type ProgressLimits struct {
	EventsPerSecond int `json:"eventsPerSecond,omitempty"`
	BytesPerSecond  int `json:"bytesPerSecond,omitempty"`
}

ProgressLimits is the rate at which a call may report. Zero fields use the defaults. It travels in the request so both ends apply the same limits.

func ProgressLimitsFrom

func ProgressLimitsFrom(ctx context.Context) (limits ProgressLimits, ok bool)

ProgressLimitsFrom returns the event rate the host set for the call being handled, with defaults filled in. A handler that streams a long output can coalesce lines to stay inside it instead of letting the rate limit drop events. ok is false when the operation did not declare progress.

func (ProgressLimits) Resolved

func (l ProgressLimits) Resolved() ProgressLimits

Resolved fills in defaults.

func (ProgressLimits) Validate

func (l ProgressLimits) Validate() error

Validate bounds explicit limits.

type ProgressReporter

type ProgressReporter interface {
	// Report sends one event. What each error means for the call:
	//
	//	nil                  sent
	//	ErrProgressDropped   the rate limit dropped it and counted it; the call
	//	                     is fine, so treat it as sent (or slow down)
	//	ErrUnsupported       the operation did not declare progress, so no event
	//	                     will ever flow: stop reporting and return the text in
	//	                     the result instead
	//	ErrInvalid           the event breaks the rules (kind, stream, text bound
	//	                     or UTF-8); the caller's bug, nothing was sent
	//	ErrClosed            the call is over, or the connection closed
	//	any other error      the connection is failing; the call will fail
	//
	// Only ErrProgressDropped is routine. An operation that declared progress
	// is always given a working reporter, whether or not the host asked for the
	// events: a host that calls it with plain Call simply discards them.
	Report(Progress) error
}

ProgressReporter sends events from inside a call.

func ProgressFrom

func ProgressFrom(ctx context.Context) ProgressReporter

ProgressFrom returns the reporter for the call being handled. It never returns nil: without one, Report returns ErrUnsupported.

type ProgressSink

type ProgressSink interface {
	// Deliver passes one event on. delivered is false when the rate limit
	// dropped it. An error is a protocol violation.
	Deliver(Progress) (delivered bool, err error)
}

ProgressSink receives the events of one call on the host side.

func ProgressSinkFrom

func ProgressSinkFrom(ctx context.Context) ProgressSink

ProgressSinkFrom returns the sink for the call being made, or nil.

type RemoteError

type RemoteError struct {
	Code                   string `json:"code"`
	Message                string `json:"message"`
	RetryAfterMilliseconds int64  `json:"retryAfterMilliseconds,omitempty"`
}

RemoteError carries a stable machine-readable category. Its text is untrusted diagnostic data and must not be projected into public state.

func (*RemoteError) Error

func (e *RemoteError) Error() string

type Request

type Request struct {
	APIVersion string          `json:"apiVersion"`
	ID         string          `json:"id"`
	Plugin     Identity        `json:"plugin"`
	Contract   ContractRef     `json:"contract"`
	Operation  string          `json:"operation"`
	Surface    string          `json:"surface,omitempty"`
	Deadline   time.Time       `json:"deadline"`
	Payload    json.RawMessage `json:"payload,omitempty"`
	// Progress carries the event rate of a call whose operation declared
	// progress. It is absent otherwise.
	Progress *ProgressLimits `json:"progress,omitempty"`
	// Parent names the forward call a reverse call belongs to. It is set only on
	// the request a host's reverse handler receives, and empty for a
	// session-scoped call.
	Parent string `json:"parent,omitempty"`
}

func (Request) Clone

func (r Request) Clone() Request

type Requirement

type Requirement struct {
	// Provider selects a package ID across revisions, exclusive with Identity.
	Provider string
	// Identity optionally pins the complete identity, never a partial match.
	Identity  *Identity
	Contract  ContractRef
	Operation string
}

type Response

type Response struct {
	APIVersion string          `json:"apiVersion"`
	ID         string          `json:"id"`
	Payload    json.RawMessage `json:"payload,omitempty"`
	Error      *RemoteError    `json:"error,omitempty"`
}

func (Response) Validate

func (r Response) Validate(requestID string) error

type ReverseBackend

type ReverseBackend interface {
	Backend
	SetReverse(ReverseHost)
}

ReverseBackend is implemented by a backend that can carry reverse frames. Open calls SetReverse before the handshake when the host configured Reverse.

type ReverseCaller

type ReverseCaller interface {
	Call(context.Context, ContractRef, string, json.RawMessage) (json.RawMessage, error)
}

ReverseCaller calls an operation the host offers. It has the method set of author.Caller, so author.Call works with it unchanged.

func ReverseFrom

func ReverseFrom(ctx context.Context) ReverseCaller

ReverseFrom returns the caller for reverse calls scoped to the current call, or nil when the host offers none.

func SessionReverseFrom

func SessionReverseFrom(ctx context.Context) ReverseCaller

SessionReverseFrom returns the caller for session-scoped reverse calls, valid until the connection closes, so background work can keep it after the call that obtained it returns. It is nil when the host offers none.

type ReverseHost

type ReverseHost interface {
	// AdmitReverse performs the cheap checks and reserves a slot. It returns
	// either an immediate result, or run, which executes the handler and may be
	// called on another goroutine; run must be called exactly once. A non-nil
	// error is a protocol violation the backend must treat as fatal.
	AdmitReverse(ReverseRequestFrame) (run func() ReverseResult, immediate *ReverseResult, err error)
}

ReverseHost is implemented by Session. A backend that carries reverse frames (see ReverseBackend) hands each reverse request to it.

type ReverseOptions

type ReverseOptions struct {
	// Handle serves a reverse call that Authorize allowed. The context derives
	// from the context of the call in flight (or, for a session-scoped call, from
	// the context given to Open without its cancellation), so values such as
	// ReverseFrom, the deadline and cancellation carry through.
	Handle Handler
	// Authorize is required. It runs for every reverse call and receives copies.
	Authorize func(context.Context, Request) error
	// Timeout bounds a reverse call without an earlier deadline; zero uses
	// DefaultTimeout.
	Timeout time.Duration
	// MaxPayloadBytes bounds a reverse payload; zero uses
	// DefaultReversePayloadBytes. It cannot exceed MaxFrameBytes.
	MaxPayloadBytes int
	// MaxInFlight bounds concurrent reverse calls; zero uses
	// DefaultReverseInFlight.
	MaxInFlight int
}

ReverseOptions configures the services a host offers to its plugin.

type ReverseRequestFrame

type ReverseRequestFrame struct {
	Frame      string          `json:"frame"`
	APIVersion string          `json:"apiVersion"`
	ID         string          `json:"id"`
	Parent     string          `json:"parent,omitempty"`
	Contract   ContractRef     `json:"contract"`
	Operation  string          `json:"operation"`
	Deadline   time.Time       `json:"deadline"`
	Payload    json.RawMessage `json:"payload,omitempty"`
}

ReverseRequestFrame is a call from a plugin to its host.

func (ReverseRequestFrame) Validate

func (f ReverseRequestFrame) Validate() error

Validate checks the frame's shape. A failure is a protocol violation.

type ReverseResponseFrame

type ReverseResponseFrame struct {
	Frame      string          `json:"frame"`
	APIVersion string          `json:"apiVersion"`
	ID         string          `json:"id"`
	Payload    json.RawMessage `json:"payload,omitempty"`
	Error      *RemoteError    `json:"error,omitempty"`
}

ReverseResponseFrame answers one ReverseRequestFrame.

func (ReverseResponseFrame) Validate

func (f ReverseResponseFrame) Validate(id string) error

Validate checks the frame against the request id it must answer.

type ReverseResult

type ReverseResult struct {
	Payload json.RawMessage
	Error   *RemoteError
}

ReverseResult is the host's answer to a reverse request.

type Session

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

Session owns invocation admission and draining. The chosen backend or host owns process lifecycle, using pkg/ext-go/cengine/ledger/supervisor or the backend's runtime (such as go-plugin). A process restart requires a fresh Session and handshake.

func Open

func Open(ctx context.Context, selected Descriptor, opts Options) (*Session, error)

Open verifies selection before opening a backend, then checks its exact handshake. Nil policy callbacks fail closed. No global registry is used.

func (*Session) Abort

func (s *Session) Abort() error

Abort interrupts the transport immediately. The owning host must separately stop any process through its supervisor. It is safe alongside Call or Close.

func (*Session) AdmitReverse

func (s *Session) AdmitReverse(frame ReverseRequestFrame) (func() ReverseResult, *ReverseResult, error)

AdmitReverse implements ReverseHost for a backend that carries frames.

func (*Session) Call

func (s *Session) Call(ctx context.Context, contract ContractRef, operation string, payload json.RawMessage) (json.RawMessage, error)

Call derives identity, surface, deadline, and a fresh correlation ID from host state. A payload cannot expand the selected descriptor. Request IDs do not supply idempotency, authorization, or automatic retries.

func (*Session) CallProgress

func (s *Session) CallProgress(ctx context.Context, contract ContractRef, operation string, payload json.RawMessage, onProgress func(Progress), options ...CallOptions) (json.RawMessage, error)

CallProgress is Call for an operation that declares progress: onProgress receives its events while the call runs, on the connection's reader, so it must not block. The final result is unchanged. Events beyond the rate limit are dropped and counted: the next event carries Dropped, and a last event with the remaining count arrives before the call returns. For an operation that did not declare progress, onProgress is never called.

func (*Session) Close

func (s *Session) Close(ctx context.Context) error

Close first rejects new invocations, then drains admitted work. A deadline while draining reopens admission without closing the backend. Concurrent Close attempts receive ErrDraining. An already closed session is idempotent.

func (*Session) Descriptor

func (s *Session) Descriptor() Descriptor

func (*Session) Done

func (s *Session) Done() <-chan struct{}

Done is closed once the session's backend has been closed, whether by Close, Abort or a failed call. Anything whose lifetime is tied to the session (for example an admitted data endpoint) ends when it closes.

func (*Session) State

func (s *Session) State() State

type State

type State string
const (
	StateReady    State = "ready"
	StateDraining State = "draining"
	StateClosed   State = "closed"
	StateFailed   State = "failed"
)

Directories

Path Synopsis
Package endpoint is the standard form of a loopback data endpoint that a plugin result declares and a host admits or refuses.
Package endpoint is the standard form of a loopback data endpoint that a plugin result declares and a host admits or refuses.
guest
author
Package author supplies typed operations and immutable guest construction.
Package author supplies typed operations and immutable guest construction.
capability
Package capability contains optional, independently versioned SDK contracts.
Package capability contains optional, independently versioned SDK contracts.
instance
Package instance manages configured resources independently of processes and connections.
Package instance manages configured resources independently of processes and connections.
stream
Package stream provides a pull-based, bounded stream contract over any Ext unary backend.
Package stream provides a pull-based, bounded stream contract over any Ext unary backend.
host
adapter
Package adapter is the host side of the adapter system: manifests, the installed-adapter store, package lifecycle, trust checks and executable invocation.
Package adapter is the host side of the adapter system: manifests, the installed-adapter store, package lifecycle, trust checks and executable invocation.
adapter/adaptercmd
Package adaptercmd provides the shared ext adapter management command.
Package adaptercmd provides the shared ext adapter management command.
home
Package home resolves Ext's shared per-user package roots.
Package home resolves Ext's shared per-user package roots.
nativego
Package nativego loads trusted Go shared objects built with -buildmode=plugin.
Package nativego loads trusted Go shared objects built with -buildmode=plugin.
process
Package process starts a plugin as a child process and binds it to the JSON-line protocol over its stdin and stdout.
Package process starts a plugin as a child process and binds it to the JSON-line protocol over its stdin and stdout.
store
Package store installs, upgrades, lists and removes reviewed packages under a caller-supplied root.
Package store installs, upgrades, lists and removes reviewed packages under a caller-supplied root.
storelayout
Package storelayout describes how an application locates a manifest inside a package.
Package storelayout describes how an application locates a manifest inside a package.
trust
Package trust is the pure-Go reference for the C engine's scoped package trust records.
Package trust is the pure-Go reference for the C engine's scoped package trust records.
Package interop plans explicit transport connections between Ext peers.
Package interop plans explicit transport connections between Ext peers.
Package packagekit supplies portable manifests and dependency preflight.
Package packagekit supplies portable manifests and dependency preflight.
author
Package author builds and seals packages without selecting a product or contract.
Package author builds and seals packages without selecting a product or contract.
Package plugintest supplies a reusable conformance suite for Ext backends.
Package plugintest supplies a reusable conformance suite for Ext backends.
enginetest
Package enginetest holds the differential checks that hold an engine of the shared C implementation against the pure-Go engine, which is the oracle: the same documents, requests, schemas and endpoints are judged by both, and the answers must agree.
Package enginetest holds the differential checks that hold an engine of the shared C implementation against the pure-Go engine, which is the oracle: the same documents, requests, schemas and endpoints are judged by both, and the answers must agree.
transport
bridge
Package bridge exposes a verified Ext backend as a Ext endpoint.
Package bridge exposes a verified Ext backend as a Ext endpoint.
inprocess
Package inprocess binds a trusted endpoint without IPC.
Package inprocess binds a trusted endpoint without IPC.
jsonline
Package jsonline binds ext.io.pc/v1 to bounded newline-delimited JSON over a caller-owned duplex connection (for example, local IPC or process pipes).
Package jsonline binds ext.io.pc/v1 to bounded newline-delimited JSON over a caller-owned duplex connection (for example, local IPC or process pipes).
validate
jsonschema
Package jsonschema validates JSON values against a bounded, offline subset of JSON Schema 2020-12 given as raw JSON.
Package jsonschema validates JSON values against a bounded, offline subset of JSON Schema 2020-12 given as raw JSON.
schema
Package schema defines a deliberately bounded schema vocabulary for plugin payloads and configuration.
Package schema defines a deliberately bounded schema vocabulary for plugin payloads and configuration.

Jump to

Keyboard shortcuts

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