resourcev2

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: AGPL-3.0 Imports: 29 Imported by: 1 module, 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 resourcev2 defines the handwritten, provider-neutral resource API. This API is an implementation candidate awaiting public-contract review, not an approved contract. Plugin-author guides start at docs/README.md in the SDK repository. docs/resource-v2-api.md is the API reference; advanced ownership and admission rules live in docs/resource-v2-contracts.md.

Provider construction

Provider requires only Catalog. Getter, Enumerator, NativeQuerier, Mutator, Actioner, connection lifecycle, and ancillary traits are independently optional. Method presence does not advertise support: the catalog qualifies each operation by type and scope. Create, mutation update, and delete have separate capabilities; OperationUpdate means advisory updates, never a write. Controller is optional. It supplies one native-client registry, admission, leases, and retirement fences. The executable examples show catalog-only and get-only composition, controller startup/stop, and generation issuance without Controller.

Identity and admission

A connection is an explicit access route, not resource identity. Only the host issues authority; NativeAuthorityHint and Session labels are not grants. Callers pin the exact catalog observation used for admission. A matching provider/route-qualified pin takes precedence over the default pin, even when stale; duplicates fail closed. Pins never authorize work or refresh themselves. Custom providers own their source generation and use NewCatalogBindingEpoch and BindCatalogRevision; CatalogBindingEpoch is an integration accessor, not permission to parse opaque tokens.

Lifetimes and ownership

Controller owns configured connections and active native generations. Start does not follow from discovery or a utility call. WithConnection supplies an owned configured-profile snapshot under an active lease; WithClient supplies the registered native client. Retirement cancels leased work, waits for it to finish, then destroys that client. Callbacks must honor cancellation and must not synchronously retire their own leased generation. Independent requests can invoke callbacks concurrently; shared native clients require synchronization. Do not mutate request/result containers concurrently with SDK use or retain callback containers for later mutation. Watch targets and connection snapshots have independent ownership; native opaque handles do not become copyable.

Honest results

SourcePage is a finite acquisition page, not a final host query page. Unknown counts, partial coverage, unavailable schemas, and source consistency remain explicit. Empty oneOf matches nothing, not any scope. Cursors are opaque source continuations. Advisory updates provide neither replay continuity nor an atomic snapshot/watch handoff. ResourceOperationError public text must be safe to expose; raw diagnostics belong in Err and host redaction remains final. Generated messages, adapters, and wire validation belong to transport, not provider construction. Wire ceilings are safety bounds, not planner budgets or promises of history, search, schema normalization, or strong live continuity.

Index

Examples

Constants

View Source
const (
	// ContinuityConnectionLocal makes no identity continuity claim across connections.
	ContinuityConnectionLocal = "connectionLocal"
	// ContinuityStableNative claims native identity continuity; the host still assigns authority.
	ContinuityStableNative = "stableNative"
)
View Source
const (

	// ResourceWirePolicy names the finite implementation-candidate wire policy,
	// independent of the host's smaller predicate/projection policy.
	ResourceWirePolicy = "omniview.resource-wire-policy.v1"
	MaxMessageBytes    = 32 << 20
	MaxDocumentBytes   = maxDocumentBytes
	MaxValueDepth      = maxDomainDepth
	MaxValueNodes      = maxDomainNodes
	MaxWireFields      = maxDomainFields
	MaxPageRecords     = maxPageRecords
	MaxPageBodyBytes   = MaxMessageBytes
)

These finite ceilings apply independently of the host's predicate policy.

View Source
const BestEffortGuarantee = "bestEffort"

BestEffortGuarantee labels the existing advisory update workflow. It provides no atomic snapshot/update cutover, replay, gap detection, or continuity proof. P05 owns stronger SourceSession semantics; a finite page is not a subscription.

View Source
const MaxCatalogRevisionBytes = 4096

MaxCatalogRevisionBytes bounds trusted admission context and its wire encoding.

View Source
const MaxCatalogRevisionMetadataBytes = 32 * 1024

MaxCatalogRevisionMetadataBytes bounds all catalog admission metadata together.

View Source
const MaxRelationshipTargets = 256

MaxRelationshipTargets is the bounded implementation-candidate ceiling for explicit relationship bindings, independent of inventory cardinality.

View Source
const WireVersion uint32 = 2

WireVersion identifies the resource transport contract, not a catalog revision.

Variables

View Source
var AllSyncPolicies = []struct {
	Value  SyncPolicy
	TSName string
}{
	{SyncOnConnect, "ON_CONNECT"}, {SyncOnFirstQuery, "ON_FIRST_QUERY"}, {SyncNever, "NEVER"},
}

AllSyncPolicies maps startup policies to UI names. Treat this shared table as read-only; policy selection does not advertise a catalog capability.

View Source
var AllWatchStates = []struct {
	Value  WatchState
	TSName string
}{
	{
		WatchStateIdle,
		"IDLE",
	},
	{WatchStateSyncing, "SYNCING"},
	{WatchStateSynced, "SYNCED"},
	{WatchStateError, "ERROR"},
	{WatchStateStopped, "STOPPED"},
	{WatchStateFailed, "FAILED"},
	{WatchStateForbidden, "FORBIDDEN"},
	{WatchStateSkipped, "SKIPPED"},
}

AllWatchStates maps lifecycle values to UI names. Treat this shared table as read-only; its order and size do not describe any source's current state.

Functions

func BindCatalogRevision

func BindCatalogRevision(bindingEpoch, nativeRevision string) (string, error)

BindCatalogRevision frames a native catalog revision under its actual source binding. The provider must own the epoch's lifetime; servers never invent one.

func CatalogBindingEpoch

func CatalogBindingEpoch(revision string) (string, error)

CatalogBindingEpoch returns the opaque client-slot epoch of an SDK-owned catalog revision. Native catalog changes do not change this epoch; replacing the native client always does. Callers must not parse revision tokens.

func CatalogRevisionForRouteFromContext

func CatalogRevisionForRouteFromContext(ctx context.Context, provider string, route AccessRoute) (string, bool)

CatalogRevisionForRouteFromContext selects the qualified observation first, falling back only when that provider/route has no qualified entry.

func CatalogRevisionFromContext

func CatalogRevisionFromContext(ctx context.Context) (string, bool)

CatalogRevisionFromContext returns the default observation and its presence. Presence does not validate syntax or authorize dispatch; route-qualified lookup is separate.

func CheckCatalogRevision

func CheckCatalogRevision(ctx context.Context, catalog Catalog) error

CheckCatalogRevision rejects stale or absent observations before dispatch.

func CheckCatalogRevisionForRoute

func CheckCatalogRevisionForRoute(ctx context.Context, catalog Catalog, route AccessRoute) error

CheckCatalogRevisionForRoute selects a qualified observation, when supplied, otherwise the explicit default observation. Missing or duplicate pins fail closed. Observation equality does not establish authorization or native client ownership.

func CloneConnection

func CloneConnection(connection types.Connection) types.Connection

CloneConnection copies mutable configured-profile containers without JSON roundtripping or scalar coercion. It preserves nils and concrete scalar types and copies exported credential fields even when tagged json:"-". Unexported implementation state and opaque runtime handles retain native ownership; this is not a general-purpose native-client clone. Map/slice/array containers in Client are copied. Do not mutate input concurrently with copying. Cloning neither validates configuration nor applies it to a registry.

func ErrorCode

func ErrorCode(err error) string

ErrorCode finds a reviewed classification through wrapping. It maps cancellation and deadlines explicitly, nil to empty, and unknown errors to INTERNAL.

func IsErrorCode

func IsErrorCode(code string) bool

IsErrorCode accepts the existing C02 provider-classification vocabulary. Unknown peer/provider codes never widen the host's canonical error contract.

func NativeFromValue

func NativeFromValue(v Value) (any, error)

NativeFromValue returns exact native scalar types and independent containers. Consumers with a narrower native domain must reject unsupported scalar types; they must not silently convert uint64 or timestamps through JSON numbers.

func NewCatalogBindingEpoch

func NewCatalogBindingEpoch() (string, error)

NewCatalogBindingEpoch issues an opaque native-source binding epoch. Custom providers retain it for one actual source/configuration generation and rotate it when that binding changes, not when native catalog data changes. A fixed stateless provider issues one epoch per provider instance.

Example
package main

import (
	"context"
	"fmt"

	resourcev2 "github.com/omniviewdev/plugin-sdk/pkg/resource/v2"
)

// generatedProvider is immutable after construction. A real mutable provider
// must synchronize publication and fence operations against generation retirement.
type generatedProvider struct{ catalog resourcev2.Catalog }

func (p *generatedProvider) Catalog(
	ctx context.Context,
	request resourcev2.CatalogRequest,
) (resourcev2.Catalog, error) {
	if request.Route.Connection != "profile" {
		return resourcev2.Catalog{}, resourcev2.NewError("NOT_FOUND", "Unknown connection.")
	}

	return p.catalog, ctx.Err()
}

func main() {
	// Issue once per actual source/configuration generation, not per Catalog call.
	epoch, err := resourcev2.NewCatalogBindingEpoch()
	if err != nil {
		panic(err)
	}
	revision, err := resourcev2.BindCatalogRevision(epoch, "native-metadata-1")
	if err != nil {
		panic(err)
	}
	provider := &generatedProvider{
		catalog: resourcev2.Catalog{
			Provider: "custom",
			Revision: revision,
			Coverage: resourcev2.Coverage{Kind: "complete"},
		},
	}
	catalog, err := provider.Catalog(
		context.Background(),
		resourcev2.CatalogRequest{Route: resourcev2.AccessRoute{Connection: "profile"}},
	)
	if err != nil {
		panic(err)
	}
	observedEpoch, err := resourcev2.CatalogBindingEpoch(catalog.Revision)
	fmt.Println(observedEpoch == epoch, err)
}
Output:
true <nil>

func NewError

func NewError(code, detail string) error

NewError constructs a classified error whose Message is detail. Both code and detail are provider assertions, not host authority. Use a reviewed IsErrorCode code and public-safe detail; attach raw native diagnostics through ResourceOperationError.Err instead. This function does not validate or redact detail, and host redaction remains authoritative.

func PtrFloat64

func PtrFloat64(v float64) *float64

PtrFloat64 distinguishes a present numeric bound, including zero, from absence.

func QualifiedCatalogRevisionFromContext

func QualifiedCatalogRevisionFromContext(ctx context.Context, provider string, route AccessRoute) (string, bool)

QualifiedCatalogRevisionFromContext never falls back to a source observation. Duplicate entries return an empty but present revision so admission fails closed.

func RecordWireSize

func RecordWireSize(r Record) (int, error)

RecordWireSize reports exact protobuf Record bytes without building a second record tree. The enclosing page/frame still includes its own metadata.

func SameConnectionClientConfig

func SameConnectionClientConfig(a, b types.Connection) bool

SameConnectionClientConfig compares source-affecting endpoint/auth configuration. Labels and Lifecycle are IDE organization/orchestration, not client inputs; display fields, refresh/expiry bookkeeping and opaque runtime Client are not source identity. Native client builders must keep endpoint/auth in Data or private sensitive data. This does not establish native authority continuity. Nil and empty configuration containers are distinct under this comparison. Keep both inputs stable during comparison. Equality only decides client reuse; it neither compares current network state nor authorizes resource access.

func ToProtoAccessRoute

func ToProtoAccessRoute(v AccessRoute) (*resourcepb.AccessRoute, error)

ToProtoAccessRoute encodes an explicit connection route without resolving or authorizing it. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoActionRequest

func ToProtoActionRequest(v ActionRequest) (*resourcepb.ActionInput, error)

ToProtoActionRequest encodes action intent and canonical input without authorization or execution. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoCatalog

func ToProtoCatalog(v Catalog) (*resourcepb.Catalog, error)

ToProtoCatalog encodes catalog declarations and coverage without granting capabilities. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoCatalogRequest

func ToProtoCatalogRequest(v CatalogRequest) (*resourcepb.AccessRoute, error)

ToProtoCatalogRequest encodes the requested catalog route without connection discovery. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoEditorSchema

func ToProtoEditorSchema(v EditorSchema) (*resourcepb.EditorSchema, error)

ToProtoEditorSchema encodes editor metadata and schema availability without fetching document references. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoEnumerateRequest

func ToProtoEnumerateRequest(v EnumerateRequest) (*resourcepb.EnumerateInput, error)

ToProtoEnumerateRequest encodes target scope and opaque pagination without fetching records. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoGetRequest

func ToProtoGetRequest(v GetRequest) (*resourcepb.GetInput, error)

ToProtoGetRequest encodes an explicit route, reference, and representation without dispatch. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoMutationRequest

func ToProtoMutationRequest(v MutationRequest) (*resourcepb.MutationInput, error)

ToProtoMutationRequest encodes mutation intent and expected revision without authorization or execution. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoNativeQueryRequest

func ToProtoNativeQueryRequest(v NativeQueryRequest) (*resourcepb.NativeQueryInput, error)

ToProtoNativeQueryRequest encodes an opaque native query and target without executing it. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoReadTarget

func ToProtoReadTarget(v ReadTarget) (*resourcepb.ReadTarget, error)

ToProtoReadTarget encodes route-qualified scope without catalog admission. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoRecord

func ToProtoRecord(v Record) (*resourcepb.Record, error)

ToProtoRecord encodes body, representation, coverage, and source revision independently. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoRelationshipDescriptor

func ToProtoRelationshipDescriptor(v RelationshipDescriptor) (*resourcepb.RelationshipDescriptor, error)

ToProtoRelationshipDescriptor encodes relationship metadata and validated extractor JSON without resolving targets. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoRelationshipResolutionRequest

func ToProtoRelationshipResolutionRequest(
	v RelationshipResolutionRequest,
) (*resourcepb.RelationshipResolutionInput, error)

ToProtoRelationshipResolutionRequest encodes source and explicit target bindings without admitting their catalog observations. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoResolvedRelationship

func ToProtoResolvedRelationship(v ResolvedRelationship) (*resourcepb.ResolvedRelationship, error)

ToProtoResolvedRelationship encodes a descriptor and explicit targets without cross-route admission. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoResourceEvent

func ToProtoResourceEvent(v ResourceEvent) (*resourcepb.ResourceEvent, error)

ToProtoResourceEvent encodes event severity and timestamps without establishing replay continuity. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoResourceHealth

func ToProtoResourceHealth(v ResourceHealth) (*resourcepb.ResourceHealth, error)

ToProtoResourceHealth encodes health conditions and observation times without probing native health. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoResourceReference

func ToProtoResourceReference(v ResourceReference) (*resourcepb.ResourceReference, error)

ToProtoResourceReference encodes canonical identity and optional incarnation without selecting access. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoSchemaDocument

func ToProtoSchemaDocument(v SchemaDocument) (*resourcepb.SchemaDocument, error)

ToProtoSchemaDocument encodes schema bytes and reference without resolving external documents. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoSchemaDocumentReference

func ToProtoSchemaDocumentReference(v SchemaDocumentReference) (*resourcepb.SchemaDocumentReference, error)

ToProtoSchemaDocumentReference encodes an opaque schema document identity and revision without fetching it. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoSourcePage

func ToProtoSourcePage(v SourcePage) (*resourcepb.SourcePage, error)

ToProtoSourcePage encodes records, coverage, exact count intent, and opaque cursor independently. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoValue

func ToProtoValue(v Value) (*resourcepb.Value, error)

ToProtoValue encodes canonical scalar kinds and exact integer values. These synchronous transport codecs perform no I/O and have no cancellation or shared mutable state. Concurrent calls are safe only while callers keep each input's mutable storage unchanged. Successful outputs do not alias input containers. Discard output on any error: malformed shapes and semantic violations return INVALID_REQUEST; safety ceiling violations return RESOURCE_LIMIT; unknown fields return UNSUPPORTED. No codec admits catalog observations or authorizes operations.

FromProto codecs reject nil messages, unknown fields, and missing selections. Scope normalization follows duplicate checks. These in-memory checks cannot replace raw-wire validation before protobuf decoding: decoding can erase duplicate singular fields and conflicting oneof selections.

ToProtoValue encodes canonical scalar kinds and exact integer values. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoWatchAddPayload

func ToProtoWatchAddPayload(v WatchAddPayload) (*resourcepb.WatchAddPayload, error)

ToProtoWatchAddPayload encodes advisory ADD data without establishing listener readiness or continuity. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoWatchConnectionSummary

func ToProtoWatchConnectionSummary(v WatchConnectionSummary) (*resourcepb.WatchConnectionSummary, error)

ToProtoWatchConnectionSummary encodes per-type advisory states and counts without starting watches. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoWatchDeletePayload

func ToProtoWatchDeletePayload(v WatchDeletePayload) (*resourcepb.WatchDeletePayload, error)

ToProtoWatchDeletePayload encodes advisory DELETE identity and optional last-known record without replay guarantees. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoWatchStateEvent

func ToProtoWatchStateEvent(v WatchStateEvent) (*resourcepb.WatchStateEvent, error)

ToProtoWatchStateEvent encodes advisory source state without changing source lifecycle. It validates before encoding, returns nil on error, and owns output storage.

func ToProtoWatchUpdatePayload

func ToProtoWatchUpdatePayload(v WatchUpdatePayload) (*resourcepb.WatchUpdatePayload, error)

ToProtoWatchUpdatePayload encodes advisory UPDATE data without establishing listener readiness or continuity. It validates before encoding, returns nil on error, and owns output storage.

func ValidateActionDescriptorRequest

func ValidateActionDescriptorRequest(request ActionRequest, descriptor ActionDescriptor, streaming bool) error

ValidateActionDescriptorRequest checks the advertised target, lane, and input.

func ValidateActionDescriptors

func ValidateActionDescriptors(v []ActionDescriptor) error

ValidateActionDescriptors checks unique action IDs, explicit scopes, and bounded parameter and output schemas.

func ValidateActionInput

func ValidateActionInput(d ActionDescriptor, v Value) error

ValidateActionInput checks declared action input without applying defaults.

func ValidateActionOutput

func ValidateActionOutput(d ActionDescriptor, v Value) error

ValidateActionOutput checks declared successful action output.

func ValidateActionRequest

func ValidateActionRequest(v ActionRequest) error

ValidateActionRequest checks exactly one target, route, action token, and tagged input.

func ValidateAddress

func ValidateAddress(a ResourceAddress, declared ...[]Dimension) error

ValidateAddress checks canonical identity shape and duplicate dimensions. An optional declaration requires exactly its dimensions and empty-value rules.

func ValidateCatalog

func ValidateCatalog(c Catalog) error

ValidateCatalog checks type, representation, schema, and scoped capability declarations. It validates structure, not caller authorization or live source availability.

func ValidateCatalogRevision

func ValidateCatalogRevision(revision string) error

ValidateCatalogRevision checks bounded observation syntax, not authorization.

func ValidateConnectionOverlay

func ValidateConnectionOverlay(overlay ConnectionOverlay) error

ValidateConnectionOverlay checks metadata bounds and unique, nonempty IDs across both entry sets. It accepts a zero overlay and does not mutate or retain inputs. Success does not verify credentials, native connectivity, or access authority.

func ValidateEnumerateRequest

func ValidateEnumerateRequest(v EnumerateRequest) error

ValidateEnumerateRequest checks target shape, optional cursor, and the page-size ceiling.

func ValidateFeatures

func ValidateFeatures(f FeatureSet) error

ValidateFeatures rejects duplicate or unknown trait names without changing f. Unknown traits return UNSUPPORTED; malformed duplicates return INVALID_REQUEST.

func ValidateGetRequest

func ValidateGetRequest(v GetRequest) error

ValidateGetRequest requires an explicit route, canonical reference, and representation. Catalog support and accepted revision checks belong to operation admission.

func ValidateJSON

func ValidateJSON(data []byte) error

ValidateJSON applies the raw message ceiling and exact structural budgets. Tagged values, native resource JSON and schema documents independently use the smaller body ceiling before their semantic admission.

func ValidateMetadata

func ValidateMetadata(v any) error

ValidateMetadata bounds JSON-visible metadata before callers marshal shared connection or presentation DTOs. Hidden credentials and json:"-" fields do not belong to the output and are never traversed.

func ValidateMutationRequest

func ValidateMutationRequest(v MutationRequest) error

ValidateMutationRequest checks reference, operation token, revision presence, and input shape. It does not infer supported mutation verbs from the request.

func ValidateNativeQueryInput

func ValidateNativeQueryInput(descriptor ResourceType, request NativeQueryRequest) error

ValidateNativeQueryInput checks declared language constraints without changing canonical Value kinds. An empty discovery list preserves opaque legacy queries; once descriptors are advertised, only declared languages are admitted.

func ValidateNativeQueryRequest

func ValidateNativeQueryRequest(v NativeQueryRequest) error

ValidateNativeQueryRequest checks enumeration bounds, language, and a lossless query value.

func ValidateOperationResult

func ValidateOperationResult(request any, result any, descriptor ResourceType) error

ValidateOperationResult binds finite provider output to its admitted request and catalog descriptor. Native source cursors remain opaque source tokens. Pass matching domain request/result values, not pointers; nil or mismatched result types fail validation. This checks shapes and binding, not authorization, current catalog equality, side-effect success, or source continuity.

func ValidateRecord

func ValidateRecord(r Record) error

ValidateRecord requires a map-root body plus valid identity, representation, and coverage.

func ValidateRelationshipResolutionRequest

func ValidateRelationshipResolutionRequest(req RelationshipResolutionRequest) error

ValidateRelationshipResolutionRequest admits explicit bindings, not permissions.

func ValidateRelationshipResolutionResult

func ValidateRelationshipResolutionResult(req RelationshipResolutionRequest, results []ResolvedRelationship) error

ValidateRelationshipResolutionResult rejects the whole result if any observed link escapes its explicit target binding. It never filters links.

func ValidateResolvedActionOutput

func ValidateResolvedActionOutput(descriptor *ActionDescriptor, value Value) error

ValidateResolvedActionOutput validates only constraints actually discovered.

func ValidateResourceDefinition

func ValidateResourceDefinition(v ResourceDefinition) error

ValidateResourceDefinition bounds and admits presentation metadata before transport serialization. Extractors never confer identity or access.

func ValidateResourceGroups

func ValidateResourceGroups(v []ResourceGroup) error

ValidateResourceGroups rejects duplicate groups and repeated resource types within each group.

func ValidateSchema

func ValidateSchema(s Schema) error

ValidateSchema checks the restricted object-root ancillary schema. Defaults, coercion, item schemas, and other JSON Schema keywords are unsupported.

func ValidateSchemaDocument

func ValidateSchemaDocument(v SchemaDocument) error

ValidateSchemaDocument checks document identity, dialect, and strict bounded JSON. It performs no external document resolution or schema normalization.

func ValidateSchemaUnavailableReason

func ValidateSchemaUnavailableReason(reason string) error

ValidateSchemaUnavailableReason admits only bounded, safe machine codes. It never transports provider messages, URLs, credentials or diagnostics.

func ValidateSchemaValue

func ValidateSchemaValue(s Schema, v Value) error

ValidateSchemaValue validates without changing values or their numeric kinds. Undeclared object properties and array elements remain unconstrained.

func ValidateScope

func ValidateScope(s QueryScope, declared ...[]Dimension) error

ValidateScope checks explicit any/oneOf selections without deduplicating values. An optional declaration requires every declared query dimension; empty oneOf is valid.

func ValidateSourcePage

func ValidateSourcePage(p SourcePage) error

ValidateSourcePage bounds records and aggregate protobuf frame size. Coverage, consistency, count, and continuation remain explicit source claims.

func ValidateValue

func ValidateValue(v Value) error

ValidateValue checks the active tagged payload, exact scalar syntax, and tree budgets. Inactive negative zero is a payload; list/map nil containers remain valid empty values.

func ValueWireSize

func ValueWireSize(v Value) (int, error)

ValueWireSize reports the exact generated protobuf Value size without allocating transport messages. Acquisition adapters can sum sizes before retaining another record, then apply ValidateSourcePage to the complete page.

func WithCatalogRevision

func WithCatalogRevision(ctx context.Context, revision string) context.Context

WithCatalogRevision pins the exact catalog observation accepted by the caller. A revision conveys admission context, not permission or authority.

func WithCatalogRevisionForRoute

func WithCatalogRevisionForRoute(
	ctx context.Context,
	provider string,
	route AccessRoute,
	revision string,
) context.Context

WithCatalogRevisionForRoute records an explicit provider/route observation for a source or relationship target. It takes precedence over the explicit default and never discovers or substitutes a current catalog. Duplicate route entries remain ambiguous and fail admission, even when their revisions are equal.

func WithSession

func WithSession(ctx context.Context, session Session) context.Context

WithSession stores diagnostic context without cloning mutable session members. Callers must keep shared members stable or synchronize their access.

func WithUtilityConnection

func WithUtilityConnection(
	pc *types.PluginContext,
	provider ConnectionContextProvider,
	reference *ResourceReference,
	route *AccessRoute,
	fn func(*types.PluginContext) error,
) error

WithUtilityConnection binds native utility creation/query to the sole active connection registry. Metadata selects; it cannot supply a configured profile. An actual canonical reference additionally requires the exact host-admitted catalog observation. Opaque nonreference utility inputs do not invent one. Explicit routes require a selected configured connection even without a reference.

A nil callback is invalid. With no selected connection and no reference or route, the callback runs directly and receives pc unchanged, possibly nil. A selected connection requires a nonnil provider; a canonical reference also requires that provider to implement Provider for revision checks before and after the callback. This helper neither performs Get nor authorizes the target.

A nil pc.Context uses Background for registry admission. On the admitted path, the callback receives a shallow PluginContext copy with the leased context and actual configured profile. Other PluginContext fields retain their ownership. Honor the lease context and do not synchronously retire the same generation. The callback's lease ends on return; accepted long-lived sessions need their own cancellation/retirement cleanup rather than retaining this request lease.

Types

type AccessRoute

type AccessRoute struct {
	Connection string `json:"connection"`
}

AccessRoute selects a configured connection, not an identity or permission. Connection must be explicit; an empty route never selects a default client.

func FromProtoAccessRoute

func FromProtoAccessRoute(p *resourcepb.AccessRoute) (AccessRoute, error)

FromProtoAccessRoute decodes an explicit connection route without resolving or authorizing it. It rejects nil or invalid messages; successful output owns mutable storage.

func (*AccessRoute) UnmarshalJSON

func (v *AccessRoute) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes AccessRoute, rejecting duplicate members, unknown fields, and invalid domain values.

type ActionCatalog

type ActionCatalog interface {
	GetActions(context.Context, AccessRoute, string) ([]ActionDescriptor, error)
}

ActionCatalog lists optional actions for an explicit route and resource type. Descriptors do not implement execution: Actioner or StreamingActioner and exact catalog capability admission are independently required. Nil slices mean no actions, not discovery failure. Calls may run concurrently; honor cancellation, return stable containers, and keep error text public-safe.

type ActionDescriptor

type ActionDescriptor struct {
	ID          string      `json:"id"`
	Label       string      `json:"label"`
	Description string      `json:"description"`
	Icon        string      `json:"icon"`
	Scope       ActionScope `json:"scope"`
	Streaming   bool        `json:"streaming"`
	// Nil schemas mean no schema was supplied, not that all inputs or outputs
	// have been validated. Dispatch does not fill defaults from these schemas.
	ParamsSchema *Schema `json:"paramsSchema,omitempty"`
	OutputSchema *Schema `json:"outputSchema,omitempty"`
	// Dangerous is a UI warning hint, never an authorization decision.
	Dangerous bool `json:"dangerous,omitempty"`
}

ActionDescriptor advertises one named action's presentation and input/output hints. Catalog action capability and invocation admission remain independent.

func ResolveActionDescriptor

func ResolveActionDescriptor(
	ctx context.Context,
	provider any,
	request ActionRequest,
	streaming bool,
) (*ActionDescriptor, error)

ResolveActionDescriptor retains an optional discovered declaration for validation. Nil means discovery is unavailable, not that any schema or execution hint was asserted.

func (*ActionDescriptor) UnmarshalJSON

func (v *ActionDescriptor) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects malformed, duplicate, and unsupported descriptor fields.

type ActionEvent

type ActionEvent struct {
	Type  string                  `json:"type"`
	Data  *Value                  `json:"data,omitempty"`
	Error *ResourceOperationError `json:"error,omitempty"`
}

ActionEvent carries native readiness or subsequent action output. Emit exactly one ready before progress/output; both require Data. Return setup errors before readiness rather than claiming native establishment. Errors use typed public-safe classification, never raw diagnostics in Data. Producers must not mutate nested Data after sending or close caller-owned channels; observe cancellation while sending and return to signal completion.

type ActionRequest

type ActionRequest struct {
	Route      AccessRoute       `json:"route"`
	Reference  ResourceReference `json:"reference"`
	TypeTarget *TypeActionTarget `json:"typeTarget,omitempty"`
	Action     string            `json:"action"`
	Input      Value             `json:"input"`
	// ExpectedDescriptor retains an advertised action observation across transport.
	// Nil supplies no expectation; replacement metadata requires rediscovery.
	ExpectedDescriptor *ActionDescriptor `json:"expectedDescriptor,omitempty"`
}

ActionRequest invokes an independently declared named operation on exactly one target. Input preserves canonical Value scalar kinds and remains borrowed for the call.

func FromProtoActionRequest

func FromProtoActionRequest(p *resourcepb.ActionInput) (ActionRequest, error)

FromProtoActionRequest decodes action intent and canonical input without authorization or execution. It rejects nil or invalid messages; successful output owns mutable storage.

func (ActionRequest) MarshalJSON

func (v ActionRequest) MarshalJSON() ([]byte, error)

MarshalJSON omits the unused instance reference for type-scoped actions.

func (*ActionRequest) UnmarshalJSON

func (v *ActionRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes ActionRequest, rejecting duplicate members, unknown fields, and invalid domain values.

type ActionScope

type ActionScope string

ActionScope distinguishes object actions from type-level actions. It is descriptive metadata, not authority to widen a request's admitted reference.

const (
	// ActionScopeInstance associates an action with an exact resource reference.
	ActionScopeInstance ActionScope = "instance"
	// ActionScopeType associates an action with a resource type rather than an instance.
	ActionScopeType ActionScope = "type"
)

type Actioner

type Actioner interface {
	Action(context.Context, ActionRequest) (Value, error)
}

Actioner supplies finite named actions. An interface implementation alone does not advertise action capability or establish permission to invoke an action.

type BestEffortUpdateProvider

type BestEffortUpdateProvider interface {
	// StartConnectionWatch receives the explicit host-admitted targets. This
	// prevents providers from inventing authority while auto-starting native work.
	StartConnectionWatch(context.Context, []ReadTarget) error
	// StopConnectionWatch cancels and joins sources on the explicit route.
	StopConnectionWatch(context.Context, AccessRoute) error
	// HasWatch is a lossy presence check; false cannot distinguish absence from
	// cancellation, stale admission, or an unavailable connection.
	HasWatch(context.Context, AccessRoute) bool
	GetWatchState(context.Context, AccessRoute) (*WatchConnectionSummary, error)
	// ListenForEvents requires a nonnil sink. A nil onReady skips that hook.
	// Run onReady before data delivery; its error rejects registration. Advisory
	// data arriving before readiness is dropped, never queued for replay.
	ListenForEvents(context.Context, WatchEventSink, func() error) error
	// EnsureResourceWatch retains its admitted target independently of caller
	// containers. Success does not claim a complete native cache or source total.
	EnsureResourceWatch(context.Context, ReadTarget) error
	StopResourceWatch(context.Context, AccessRoute, string) error
	RestartResourceWatch(context.Context, ReadTarget) error
	IsResourceWatchRunning(context.Context, AccessRoute, string) (bool, error)
}

BestEffortUpdateProvider ports the existing optional informer lifecycle, with canonical records and explicit advisory guarantees. It is not P05's source continuity protocol. Registration readiness precedes starting native sources; ListenForEvents blocks until cancellation and retires its sink before return. Listener cancellation retires only that listener; connection generation retirement owns native source cancellation. Implementations must observe cancellation and keep callbacks within the listener lifetime.

type Capability

type Capability struct {
	Operation Operation  `json:"operation"`
	Scope     QueryScope `json:"scope"`
	// Guarantee labels advisory update semantics; finite operations leave it
	// empty. BestEffortGuarantee does not promise replay or source continuity.
	Guarantee string `json:"guarantee,omitempty"`
}

Capability advertises one operation over an explicit query scope. Supporting create, update, or delete requires its own declaration even with one Mutator.

func (*Capability) UnmarshalJSON

func (v *Capability) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Capability, rejecting duplicate members, unknown fields, and invalid domain values.

type Catalog

type Catalog struct {
	Provider string         `json:"provider"`
	Types    []ResourceType `json:"types"`
	Revision string         `json:"revision"`
	Coverage Coverage       `json:"coverage"`
}

Catalog describes support observed through the requested route. Revision is an opaque observation used for admission, not an authorization credential. Failed or denied discovery is an error, not an empty complete catalog.

func FromProtoCatalog

func FromProtoCatalog(p *resourcepb.Catalog) (Catalog, error)

FromProtoCatalog decodes catalog declarations and coverage without granting capabilities. It rejects nil or invalid messages; successful output owns mutable storage.

func (Catalog) MarshalJSON

func (v Catalog) MarshalJSON() ([]byte, error)

MarshalJSON validates Catalog and emits canonical JSON without mutating caller-owned containers.

func (*Catalog) UnmarshalJSON

func (v *Catalog) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Catalog, rejecting duplicate members, unknown fields, and invalid domain values.

type CatalogRequest

type CatalogRequest struct {
	Route AccessRoute `json:"route"`
}

CatalogRequest discovers support through one explicit access route. Discovery does not start a connection or grant authority over the returned types.

func FromProtoCatalogRequest

func FromProtoCatalogRequest(p *resourcepb.AccessRoute) (CatalogRequest, error)

FromProtoCatalogRequest decodes the requested catalog route without connection discovery. It rejects nil or invalid messages; successful output owns mutable storage.

func (*CatalogRequest) UnmarshalJSON

func (v *CatalogRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes CatalogRequest, rejecting duplicate members, unknown fields, and invalid domain values.

type Closer

type Closer interface{ Close() error }

Closer releases provider-owned lifetime state. Callers must not assume closing an individual request closes the provider or its accepted sessions.

type ColumnDefinition

type ColumnDefinition struct {
	ID               string            `json:"id"`
	Header           string            `json:"header"`
	Accessors        string            `json:"accessor"`
	AccessorPriority string            `json:"accessorPriority,omitempty"`
	ColorMap         map[string]string `json:"colorMap,omitempty"`
	Color            string            `json:"color,omitempty"`
	Alignment        string            `json:"align,omitempty"`
	Hidden           bool              `json:"hidden,omitempty"`
	Width            int               `json:"width,omitempty"`
	Formatter        string            `json:"formatter,omitempty"`
	Component        string            `json:"component,omitempty"`
	ComponentParams  any               `json:"componentParams,omitempty"`
	ResourceLink     *ResourceLink     `json:"resourceLink,omitempty"`
	ValueMap         map[string]string `json:"valueMap,omitempty"`
}

ColumnDefinition describes client-side display and extraction hints. Accessors are presentation expressions, not canonical addresses or server query predicates. Maps, ComponentParams, and ResourceLink remain mutable caller-visible metadata.

type Config

type Config[ClientT any] struct {
	// Catalog receives the explicit route. Dynamic providers can use
	// Controller.WithClient inside this handler to discover native types.
	Catalog       func(context.Context, CatalogRequest) (Catalog, error)
	Registrations []Registration[ClientT]
	Lifecycle     *Lifecycle[ClientT]
	// ResolveRegistration optionally supplements static registrations for each
	// discovered type. It must return that exact Type and may restrict Connection
	// to the requested route, never another route. It may run repeatedly and
	// concurrently; returned scopes must remain stable during SDK use.
	ResolveRegistration func(context.Context, AccessRoute, string) (Registration[ClientT], error)
	// DynamicUpdates declares that ResolveRegistration installs real Watch
	// callbacks. It enables ancillary negotiation before connection discovery;
	// each actual target still requires catalog and callback admission.
	DynamicUpdates bool
	// ErrorClassifier runs after a registration classifier declines the error.
	// Existing typed errors and context cancellation retain their classes.
	ErrorClassifier ErrorClassifier
}

Config composes the optional Controller around required route-qualified Catalog discovery. A nil Lifecycle disables managed connections; operation callbacks then receive a nil client. Nil operation callbacks leave that operation absent, regardless of Controller's Go method set.

NewController shallow-copies Registrations, not their nested scopes or Lifecycle. Keep these construction inputs immutable afterward. Callbacks can run concurrently, including Catalog and ResolveRegistration for the same route. Synchronize captured mutable state and return independently owned results. Public error text must be safe for users; keep native diagnostics in ResourceOperationError.Err, not its title, message, or suggestions.

type ConnectionBrowser

type ConnectionBrowser interface {
	ListConnections(context.Context) ([]types.Connection, error)
	UpdateConnection(context.Context, types.Connection) (types.Connection, error)
	DeleteConnection(context.Context, string) error
	WatchConnections(context.Context, chan<- []types.Connection) error
}

ConnectionBrowser supplies connection UI workflows independently of finite resource operations. It does not imply ConnectionLifecycle or automatically start clients. Lists and watch events describe inventory, not selected access.

Calls and watches may run concurrently; synchronize shared state. Honor request cancellation and make watch sends cancellation-aware. The caller owns the watch channel: send snapshots and return, never close it. Do not mutate returned or sent containers while the receiver consumes them. Nil slices are empty inventories, not discovery failures; return an error for failed discovery. Public error fields must be safe for display; raw diagnostics belong in ResourceOperationError.Err. Remote callers must negotiate optional features rather than infer support from a transport client's static method set.

type ConnectionContextConsumer

type ConnectionContextConsumer interface {
	BindConnectionContextProvider(ConnectionContextProvider)
}

ConnectionContextConsumer receives the shared registry during SDK capability setup, before utility work begins. Bind once rather than creating a second resource registry. A source without resource composition may supply its own registry. A nil provider means managed connection admission is unavailable; selected-connection utility work must not bypass that absence.

type ConnectionContextProvider

type ConnectionContextProvider interface {
	WithConnection(context.Context, AccessRoute, func(context.Context, types.Connection) error) error
}

ConnectionContextProvider binds utility work to the sole started native-client registry without implicitly starting, probing, or selecting a connection. WithConnection requires an explicit configured route and a nonnil callback. It supplies the actual configured profile snapshot, not caller metadata.

The callback context combines caller and generation cancellation. Retirement cancels it and waits for callback return before destroying the native client. Do not retain the lease-bound context for unowned background work or retire the same generation synchronously inside the callback. Calls may run concurrently. A connection lease does not itself authorize canonical resource access.

type ConnectionLifecycle

type ConnectionLifecycle interface {
	LoadConnections(context.Context) ([]types.Connection, error)
	GetConnection(context.Context, string) (types.Connection, error)
	StartConnection(context.Context, string) (types.ConnectionStatus, error)
	StopConnection(context.Context, string) (types.Connection, error)
	CheckConnection(context.Context, string) (types.ConnectionStatus, error)
}

ConnectionLifecycle is independent of finite operations and best-effort updates. Strong source continuity remains owned by the P05 SourceSession. Configured profiles and started native clients are distinct: discovery and GetConnection do not implicitly start clients. Implementations must honor caller cancellation and own the mutable configuration returned to callers independently. CheckConnection may probe native health; readiness inspection is separate.

type ConnectionOverlay

type ConnectionOverlay struct {
	Upserts     []types.Connection `json:"upserts"`
	DisabledIDs []string           `json:"disabledIDs"`
}

ConnectionOverlay is the host's explicit desired configuration, not a native discovery snapshot. The host owns durable storage. Providers retain this only in memory and merge it over subsequent native discovery. Upserts and disabled IDs must be disjoint and unique. An empty overlay restores native discovery. Nil and empty slices both contribute no entries. A zero overlay removes all overrides and tombstones. Nil private upsert data may inherit source credentials for unchanged public client configuration; an explicit empty map clears them. Hosts must not persist source-owned private credentials.

type ConnectionOverlayProvider

type ConnectionOverlayProvider interface {
	ApplyConnectionOverlay(context.Context, ConnectionOverlay) error
	// NativeConnections returns independent latest native-discovery snapshots
	// before the overlay. It does not reload discovery or include manual profiles.
	NativeConnections(context.Context) ([]types.Connection, error)
}

ConnectionOverlayProvider replaces the entire desired overlay transactionally. It validates before mutation and cancels/drains clients for changed effective routes before returning success. Native configuration files are never changed. Hosts can reapply the previous explicit overlay if durable storage fails. Failure preserves prior desired state, not clients already retired while draining. Reapplying a prior overlay cannot restore a retired generation. Calls may serialize inventory mutation; do not synchronously reenter mutation from teardown callbacks or affected leased work.

type ConnectionReadinessProvider

type ConnectionReadinessProvider interface {
	GetConnectionStatus(context.Context, string) (types.ConnectionStatus, error)
}

ConnectionReadinessProvider reports only registered native lifecycle state. It never creates a client, probes network health or acquires a resource lease.

type Controller

type Controller[ClientT any] struct {
	// contains filtered or unexported fields
}

Controller dispatches finite source operations and independently optional best-effort updates. Strong continuity remains P05's separate contract; neither a finite handler nor advisory updates imply that guarantee. Construct it with NewController; the zero value and nil receiver are not usable. Methods require nonnil contexts. Request/result containers remain borrowed during SDK use unless a method explicitly returns a connection snapshot. Its broad method set does not advertise operations: catalog declarations, installed registrations, and ancillary feature negotiation determine support.

The controller owns one configured-client registry. configMu serializes desired inventory changes; when both locks are needed, acquire configMu before mu. mu protects registry membership, retirement flags and inventory publication. Never hold mu while invoking provider callbacks, waiting for readiness or leases, or stopping update sources. Inventory teardown still holds configMu: callbacks must not reenter inventory mutations.

Lease admission increments users under mu before retirement can begin. Retirement marks the slot stopping and cancels its context under mu, then waits outside mu for readiness, update sources and all leases before teardown. Each lease combines caller, controller and client-generation cancellation and releases its user count exactly once. Callbacks must honor cancellation and must not synchronously stop or close their own leased generation, or wait for an operation that does so. Callbacks may run concurrently across requests and connections; shared provider state needs its own synchronization.

func NewController

func NewController[T any](cfg Config[T]) (*Controller[T], error)

NewController constructs the optional controller without starting connections. It copies the registration slice, but retains nested registration scopes, lifecycle configuration and callback-owned state. Callers must keep these retained inputs immutable after construction; callbacks remain responsible for synchronizing their own mutable implementation state. Catalog is required. A nonnil Lifecycle requires load, create, and destroy callbacks; dynamic update declarations require ResolveRegistration. Invalid construction inputs return an error and no controller. Connections remain absent until explicitly loaded/applied, and unstarted until explicitly started.

func (*Controller[T]) Action

func (c *Controller[T]) Action(ctx context.Context, request ActionRequest) (value Value, err error)

Action dispatches a finite action under exact catalog/registration admission and a native lease, then fences the catalog and validates the returned Value. StreamingActioner is independent and is not invoked here. Inputs/results follow Registration's ownership rules. An error can follow a native side effect and is not evidence that replay is safe; ignore the returned Value on error.

func (*Controller[T]) ApplyConnectionOverlay

func (c *Controller[T]) ApplyConnectionOverlay(ctx context.Context, overlay ConnectionOverlay) error

ApplyConnectionOverlay replaces the entire host-owned desired overlay. Validation and client teardown must succeed before the new desired state is published. The controller never writes native configuration files. A zero overlay restores native discovery; inputs are copied. Nil private override data may inherit source credentials only for unchanged public client configuration; explicit empty private data clears it. Hosts own durable storage and startup replay and must not persist native private credentials. Failure keeps prior desired state, but canceled/drained clients remain retired. Reapplication cannot resurrect a generation. Calls serialize inventory mutation and must not reenter it from teardown callbacks or affected leased work.

func (*Controller[T]) ApplyConnections

func (c *Controller[T]) ApplyConnections(ctx context.Context, connections []types.Connection) error

ApplyConnections replaces only the native discovery snapshot. Explicit host overrides and disabled IDs survive refreshes and native disappearance. Nil replaces discovery with an empty snapshot. Inputs are copied, but callers must not mutate them during the call. Display-only edits preserve clients; changed client configuration cancels and drains old generations before publication. Teardown failure or cancellation preserves prior desired inventory, but cannot resurrect retired clients. No new clients start automatically. Do not reenter this method from inventory-teardown callbacks or leased work whose generation the replacement can retire.

func (*Controller[T]) Catalog

func (c *Controller[T]) Catalog(ctx context.Context, request CatalogRequest) (catalog Catalog, err error)

Catalog discovers one explicit route under a generation lease without starting clients or requiring an accepted catalog observation. It validates callback output, intersects advertised capabilities with installed registrations/scopes, and binds the revision to this controller or native generation. Callback containers must remain stable during SDK use; the result is not a blanket deep copy. Catalog callbacks may reenter WithClient using the supplied context, but must not synchronously retire their leased generation.

func (*Controller[T]) CheckConnection

func (c *Controller[T]) CheckConnection(ctx context.Context, id string) (status types.ConnectionStatus, err error)

CheckConnection optionally probes a configured profile under an active lease. An unstarted profile returns DISCONNECTED without starting it. A nil lifecycle CheckConnection callback reports CONNECTED registration without probing network health. A supplied callback must return the selected profile's ID; its returned profile is copied before exposure. Unknown IDs are NOT_FOUND. Cancellation includes the caller and generation; callbacks must honor it.

func (*Controller[T]) Close

func (c *Controller[T]) Close() error

Close permanently rejects new work, cancels generations and advisory sources, drains leases, and destroys clients. Repeated and concurrent calls return the same accumulated teardown error. Close has no timeout: callbacks must observe cancellation and cleanup must terminate. Never call it synchronously from a leased callback or lifecycle callback whose completion Close must await.

func (*Controller[T]) DeleteConnection

func (c *Controller[T]) DeleteConnection(ctx context.Context, id string) error

DeleteConnection hides a native route or removes a manual desired profile. Its tombstone survives native refresh until the host replaces the overlay. Unknown IDs return NOT_FOUND. Existing clients are canceled and drained before publication; failure retains prior desired state but not retired clients. This does not delete native configuration or durable host storage. Inventory teardown reentrancy restrictions from ApplyConnectionOverlay also apply.

func (*Controller[T]) EnsureResourceWatch

func (c *Controller[T]) EnsureResourceWatch(ctx context.Context, target ReadTarget) (err error)

EnsureResourceWatch admits and starts or reuses one advisory resource source. It requires exact update capability, a Watch callback, and an accepted catalog observation; SyncNever disables support. A running source can cover a narrower requested scope only with matching identity, representation, and revision. Changed targets/revisions require explicit stop and fresh admission.

Success registers the source, not native readiness or replay continuity. Admission copies retained target/descriptor containers. Accepted sources outlive request completion, retain their generation lease, and recheck admission before native retries. Explicit stop or generation retirement cancels and drains them.

func (*Controller[T]) Enumerate

func (c *Controller[T]) Enumerate(ctx context.Context, request EnumerateRequest) (page SourcePage, err error)

Enumerate acquires one bounded source page for an admitted target, not a host query result or snapshot/live handoff. It leases an already-started generation when Lifecycle is configured and requires an exact catalog capability and callback. Page size, identity, membership, representation, and catalog fences apply before success. Source cursors retain native semantics. Inputs/results follow Registration's ownership rules; ignore the page on error.

func (*Controller[T]) Features

func (c *Controller[T]) Features(ctx context.Context) (FeatureSet, error)

Features reports installed ancillary implementations rather than Controller's static method set. Wrappers with additional native traits extend this result. An empty Traits slice means no optional ancillary implementation is installed, not lack of finite catalog support. This method does not start or probe clients.

func (*Controller[T]) Get

func (c *Controller[T]) Get(ctx context.Context, request GetRequest) (record Record, err error)

Get acquires one canonical record using an explicit representation and accepted route catalog observation. It leases the native client, requires both catalog capability and a matching Get registration, then fences the catalog and validates result identity/provenance before success. It never starts a connection. Callback inputs/results follow Registration's ownership and concurrency rules. Cancellation or a retired admission can reject a callback's otherwise successful result; a nonnil error means the returned record is not accepted.

func (*Controller[T]) GetActions

func (c *Controller[T]) GetActions(ctx context.Context, route AccessRoute, typ string) ([]ActionDescriptor, error)

GetActions returns route/type descriptors whose declarations agree across scopes. Conflicting IDs are omitted because this discovery API cannot express their scope.

func (*Controller[T]) GetConnection

func (c *Controller[T]) GetConnection(ctx context.Context, id string) (types.Connection, error)

GetConnection returns an independently owned configured-profile snapshot, not a native client or a lease. Editing it does not apply configuration. Empty IDs are invalid, unknown IDs are NOT_FOUND, and absent Lifecycle is UNSUPPORTED.

func (*Controller[T]) GetConnectionStatus

func (c *Controller[T]) GetConnectionStatus(ctx context.Context, id string) (types.ConnectionStatus, error)

GetConnectionStatus snapshots the sole configured-client registry without starting, waiting, probing or performing catalog/resource work. CONNECTED means registration only, not network health or resource-source readiness. Configured unstarted profiles are DISCONNECTED, construction is PENDING, and failed startup remains FAILED until retry, stop, or meaningful replacement. Unknown IDs are NOT_FOUND; returned connection configuration is independently owned. This is a local readiness snapshot, not a lease or permission grant.

func (*Controller[T]) GetWatchState

func (c *Controller[T]) GetWatchState(ctx context.Context, route AccessRoute) (*WatchConnectionSummary, error)

GetWatchState returns an independently owned advisory summary under a generation lease and accepted catalog observation. A route with no retained source entries returns nil, NOT_FOUND. Counts remain native observations: unknown is not zero, and BestEffortGuarantee does not promise replay continuity.

func (*Controller[T]) HasWatch

func (c *Controller[T]) HasWatch(ctx context.Context, route AccessRoute) bool

HasWatch reports whether any source entry exists for an admitted route, including completed entries retained for state inspection. It does not mean a native source is currently running or healthy. Invalid routes, cancellation, lease failures, and stale/missing catalog observations all return false. Use IsResourceWatchRunning or GetWatchState when that distinction matters.

func (*Controller[T]) IsResourceWatchRunning

func (c *Controller[T]) IsResourceWatchRunning(ctx context.Context, route AccessRoute, typ string) (bool, error)

IsResourceWatchRunning snapshots the advisory manager's running flag for one explicit route/type under a generation lease and accepted catalog observation. Missing entries return false, nil; acquisition/admission errors remain errors. Running means manager activity, not native readiness, health, or continuity.

func (*Controller[T]) ListConnections

func (c *Controller[T]) ListConnections(ctx context.Context) ([]types.Connection, error)

ListConnections returns the managed connection inventory, not an implicit selection. Native inventory watching belongs to a ConnectionBrowser provider. Profiles are independently owned and sorted by ID. No discovery refresh, client start, or health probe occurs; absent Lifecycle returns UNSUPPORTED.

func (*Controller[T]) ListenForEvents

func (c *Controller[T]) ListenForEvents(ctx context.Context, sink WatchEventSink, onReady func() error) (err error)

ListenForEvents registers a listener until caller/controller cancellation or a listener failure. A nil sink is invalid; nil onReady accepts without a callback. It does not start sources. onReady must succeed before state replay and data delivery; pre-ready advisory data is dropped, not buffered for replay.

Sink callbacks can run concurrently and must return promptly. Cancellation retires this listener and waits for its admitted callbacks, not the underlying generation-owned sources. Do not synchronously stop a delivering source from its sink callback or wait there for this listener to return. Framework code owns delivery/completion; the sink must not close its channels.

func (*Controller[T]) LoadConnections

func (c *Controller[T]) LoadConnections(ctx context.Context) (connections []types.Connection, err error)

LoadConnections refreshes native discovery through Lifecycle.LoadConnections, applies that snapshot beneath the retained host overlay, and returns the effective inventory as independent snapshots sorted by ID. It never starts clients. Native discovery failure leaves the previous inventory in place; application failure follows ApplyConnections retirement semantics. A nil discovered slice is a successful empty native snapshot, not a failure.

func (*Controller[T]) Mutate

func (c *Controller[T]) Mutate(ctx context.Context, request MutationRequest) (record Record, err error)

Mutate dispatches only the requested create, update, or delete verb after exact catalog and registration admission. One Mutate callback does not advertise all verbs. The call leases the native generation and validates returned identity after the catalog fence. It never starts clients or grants resource authority. Inputs/results follow Registration's ownership rules. An error can occur after the native write, so it does not prove the side effect failed or permit blind replay; the returned record is not accepted on error.

func (*Controller[T]) NativeConnections

func (c *Controller[T]) NativeConnections(ctx context.Context) ([]types.Connection, error)

NativeConnections snapshots the latest successful native discovery before overlay application. It neither reloads discovery nor exposes manual profiles. Returned profiles are independent snapshots sorted by ID, including private configuration; hosts must not persist source-owned credentials in overlays.

func (*Controller[T]) NativeQuery

func (c *Controller[T]) NativeQuery(ctx context.Context, request NativeQueryRequest) (page SourcePage, err error)

NativeQuery invokes one admitted provider-native query and validates its bounded source page. Native query support is independent of enumeration; it is not a universal query planner. Catalog capability and a matching callback are both required. The call leases the generation without implicitly starting it and rejects stale catalog or generation results. Inputs/results follow Registration's ownership rules; ignore the page on error.

func (*Controller[T]) RestartResourceWatch

func (c *Controller[T]) RestartResourceWatch(ctx context.Context, target ReadTarget) error

RestartResourceWatch admits the target, stops its route/type source, then ensures a new source. It is not an atomic handoff: a failed restart may leave no running source, and no replay or gap-free delivery is promised. StopResourceWatch and EnsureResourceWatch lifetime/reentrancy rules apply.

func (*Controller[T]) StartConnection

func (c *Controller[T]) StartConnection(ctx context.Context, id string) (status types.ConnectionStatus, err error)

StartConnection starts one configured profile or joins its in-flight startup. The creator's cancellation cancels startup until construction completes; cancellation of another waiter only ends that wait. Accepted generations then outlive the initiating request. CreateClient and OnStart must both succeed before CONNECTED, which reports lifecycle registration, not network health.

Failure drains and destroys any returned client and retains only safe FAILED status. A later explicit call retries with a fresh generation. Unknown IDs are NOT_FOUND; lifecycle-less controllers return UNSUPPORTED. Calls may overlap readiness inspection, but callbacks must not wait on their own pending start.

func (*Controller[T]) StartConnectionWatch

func (c *Controller[T]) StartConnectionWatch(ctx context.Context, targets []ReadTarget) (err error)

StartConnectionWatch admits every supplied target before starting sources whose registration uses SyncOnConnect. Nil/empty targets are a no-op. Each target needs its accepted catalog observation; no connection starts implicitly. If starting a later source fails, earlier sources are not rolled back. Success means source registration, not native readiness or gap-free continuity. Retained targets/descriptors are copied. Sources outlive this request after acceptance and end on explicit stop, generation retirement, or controller close.

func (*Controller[T]) StopConnection

func (c *Controller[T]) StopConnection(ctx context.Context, id string) (connection types.Connection, err error)

StopConnection cancels a configured profile's generation, stops advisory sources, waits for startup and leases, then runs teardown. The profile remains configured; an already-stopped profile succeeds and clears retained startup failure status. Unknown IDs are NOT_FOUND. The returned profile is an independent snapshot.

After retirement begins, caller cancellation does not skip draining or cleanup. This can block on callbacks that ignore cancellation; never call synchronously from work holding this generation's lease or from its lifecycle callbacks.

func (*Controller[T]) StopConnectionWatch

func (c *Controller[T]) StopConnectionWatch(ctx context.Context, route AccessRoute) error

StopConnectionWatch cancels and drains every advisory source on an explicit route without stopping its client. It holds a generation lease and checks the accepted catalog observation before and after stopping; missing watches are a no-op. Cancellation after retirement begins does not skip draining. Do not call synchronously from a source callback or sink delivery being drained.

func (*Controller[T]) StopResourceWatch

func (c *Controller[T]) StopResourceWatch(ctx context.Context, route AccessRoute, typ string) error

StopResourceWatch cancels and drains the route/type source without stopping its client. Missing sources are a no-op. Exact route, type, generation lease, and accepted catalog observation are required; final admission can fail after the source has already stopped. Do not call synchronously from that source or sink.

func (*Controller[T]) UpdateConnection

func (c *Controller[T]) UpdateConnection(ctx context.Context, connection types.Connection) (types.Connection, error)

UpdateConnection upserts an explicitly identified desired record. Native refreshes cannot overwrite it; ApplyConnectionOverlay owns reset/restore. The input and returned profile own independent mutable configuration. This replaces the whole desired record, not a field patch, and clears its tombstone. Changed client configuration drains its generation before publishing; failure retains prior desired state but may leave that generation retired. See ApplyConnectionOverlay for credential inheritance and reentrancy restrictions.

func (*Controller[T]) WithClient

func (c *Controller[T]) WithClient(
	ctx context.Context,
	route AccessRoute,
	fn func(context.Context, *T) error,
) (err error)

WithClient holds an active client lease for discovery or provider-specific work. Stop and Close cancel the callback and wait before destroying its client. No implicit start, probe, default route, or resource authorization occurs. With no Lifecycle the callback receives nil; otherwise the selected generation must already be started. A nil callback is invalid. The client is borrowed only until callback return, and concurrent callbacks can share it. Honor the supplied context and never synchronously retire the same generation while holding its lease. A nil callback error does not suppress lease-context cancellation.

func (*Controller[T]) WithConnection

func (c *Controller[T]) WithConnection(
	ctx context.Context,
	route AccessRoute,
	fn func(context.Context, types.Connection) error,
) (err error)

WithConnection holds an already-connected native client generation for utility work. Metadata is only a selector; the callback receives the actual configured profile. No probe, implicit start or default selection occurs. The callback and context are lease-bound: return before retiring this generation, and do not retain native work beyond the lease without explicit session cleanup. The supplied profile owns its mutable configuration; editing it changes no registry state. A nil callback is invalid; absent Lifecycle is UNSUPPORTED. Unknown profiles are NOT_FOUND and configured unstarted profiles are CONNECTION_ERROR. Callback success still fails if its lease context was canceled.

type Count

type Count struct {
	Kind  string  `json:"kind"`
	Value *string `json:"value,omitempty"`
}

Count distinguishes unknown cardinality from an observed zero. Unknown requires nil Value; exact and estimate require a canonical unsigned 64-bit decimal string. A page's record count does not by itself establish total source cardinality.

func (*Count) UnmarshalJSON

func (v *Count) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Count, rejecting duplicate members, unknown fields, and invalid domain values.

type Coverage

type Coverage struct {
	Kind   string   `json:"kind"`
	Paths  []string `json:"paths"`
	Reason string   `json:"reason,omitempty"`
}

Coverage states known acquisition limitations, not operation success alone. Complete forbids Paths and Reason. Partial and unknown require a public-safe Reason; preserve any reported path limitations rather than claiming completeness.

func (Coverage) MarshalJSON

func (v Coverage) MarshalJSON() ([]byte, error)

MarshalJSON validates Coverage and emits canonical JSON without mutating caller-owned containers.

func (*Coverage) UnmarshalJSON

func (v *Coverage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Coverage, rejecting duplicate members, unknown fields, and invalid domain values.

type Dimension

type Dimension struct {
	Name       string `json:"name"`
	AllowEmpty bool   `json:"allowEmpty"`
}

Dimension declares a required identity or query coordinate. AllowEmpty permits the literal empty string; it does not permit omitting the coordinate.

func (*Dimension) UnmarshalJSON

func (v *Dimension) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Dimension, rejecting duplicate members, unknown fields, and invalid domain values.

type EdgeDirection

type EdgeDirection string

EdgeDirection orients a descriptor relative to the source resource. The empty value is the explicit outgoing direction, not unknown direction.

const (
	// EdgeOutgoing places the source at the origin of the relationship.
	EdgeOutgoing EdgeDirection = ""
	// EdgeIncoming places the source at the destination of the relationship.
	EdgeIncoming EdgeDirection = "incoming"
)

type EditorSchema

type EditorSchema struct {
	Type      string        `json:"type"`
	FileMatch string        `json:"fileMatch"`
	URI       string        `json:"uri"`
	Language  string        `json:"language"`
	Binding   SchemaBinding `json:"binding"`
}

EditorSchema associates editor selection metadata with an explicit schema binding. URI is editor metadata, not permission to fetch an external document; Binding distinguishes unavailable acquisition from known schema absence.

func FromProtoEditorSchema

func FromProtoEditorSchema(p *resourcepb.EditorSchema) (EditorSchema, error)

FromProtoEditorSchema decodes editor metadata and schema availability without fetching document references. It rejects nil or invalid messages; successful output owns mutable storage.

type EditorSchemaProvider

type EditorSchemaProvider interface {
	GetEditorSchemas(context.Context, AccessRoute) ([]EditorSchema, error)
}

EditorSchemaProvider lists optional editor bindings for an explicit route. Schema absence, acquisition failure, and reduced validation are distinct states in EditorSchema; an empty list does not make a validation claim. Nil slices mean no bindings. Calls may run concurrently: honor cancellation, synchronize shared state, and keep returned containers stable during SDK use. Implementing this interface does not grant create or update capability.

type EnumerateRequest

type EnumerateRequest struct {
	Target   ReadTarget `json:"target"`
	PageSize uint32     `json:"pageSize"`
	// Cursor is nil for an initial acquisition. A nonnil source token is opaque
	// and must not be reused after the target or source generation changes.
	Cursor *string `json:"cursor,omitempty"`
}

EnumerateRequest asks for one finite source page, not a subscription or a host-planned query result. A valid empty oneOf must return an empty page.

func FromProtoEnumerateRequest

func FromProtoEnumerateRequest(p *resourcepb.EnumerateInput) (EnumerateRequest, error)

FromProtoEnumerateRequest decodes target scope and opaque pagination without fetching records. It rejects nil or invalid messages; successful output owns mutable storage.

func (*EnumerateRequest) UnmarshalJSON

func (v *EnumerateRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes EnumerateRequest, rejecting duplicate members, unknown fields, and invalid domain values.

type Enumerator

type Enumerator interface {
	Enumerate(context.Context, EnumerateRequest) (SourcePage, error)
}

Enumerator supplies finite, bounded source acquisition when the scoped catalog declares enumeration. Return discovery failures as errors, not complete emptiness.

type ErrorClassifier

type ErrorClassifier interface{ ClassifyError(error) error }

ErrorClassifier can decline an error by returning nil.

type EventSeverity

type EventSeverity string

EventSeverity classifies diagnostic events, not operation errors or watch state.

const (
	// SeverityNormal marks informational resource events.
	SeverityNormal EventSeverity = "normal"
	// SeverityWarning marks resource events requiring attention.
	SeverityWarning EventSeverity = "warning"
	// SeverityError marks resource events reporting a failure.
	SeverityError EventSeverity = "error"
)

type Feature

type Feature string

Feature reports availability of an ancillary transport trait, not support for a finite operation. Finite support always comes from the qualified catalog.

const (
	// FeatureConnections enables explicit connection lifecycle operations.
	FeatureConnections Feature = "connections"
	// FeatureConnectionReadiness enables nonblocking registered-state inspection.
	FeatureConnectionReadiness Feature = "connectionReadiness"
	// FeatureConnectionBrowser enables native configured-profile discovery.
	FeatureConnectionBrowser Feature = "connectionBrowser"
	// FeatureConnectionOverlay enables replacement of the desired in-memory profile overlay.
	FeatureConnectionOverlay Feature = "connectionOverlay"
	// FeatureScopeValues enables discovery of values for declared scope dimensions.
	FeatureScopeValues Feature = "scopeValues"
	// FeaturePresentation enables resource presentation metadata.
	FeaturePresentation Feature = "presentation"
	// FeatureEditorSchemas enables editor schema bindings.
	FeatureEditorSchemas Feature = "editorSchemas"
	// FeatureSchemaDocuments enables acquisition of shared schema documents.
	FeatureSchemaDocuments Feature = "schemaDocuments"
	// FeatureRelationships enables scoped relationship resolution.
	FeatureRelationships Feature = "relationships"
	// FeatureHealth enables explicit native health acquisition, not lifecycle readiness.
	FeatureHealth Feature = "health"
	// FeatureActionCatalog enables discovery of available action descriptors.
	FeatureActionCatalog Feature = "actionCatalog"
	// FeatureStreamingActions enables ready-gated action event streams.
	FeatureStreamingActions Feature = "streamingActions"
	// FeatureBestEffortUpdates enables advisory updates without replay guarantees.
	FeatureBestEffortUpdates Feature = "bestEffortUpdates"
)

type FeatureNegotiator

type FeatureNegotiator interface {
	Features(context.Context) (FeatureSet, error)
}

FeatureNegotiator is implemented by the transport client and configurable controllers. Hosts call it before optional lifecycle/stream startup. A remote client's Go method set is never evidence that its provider supports a trait.

type FeatureSet

type FeatureSet struct {
	Traits []Feature `json:"traits"`
}

FeatureSet lists ancillary traits available on this provider or transport. Nil or empty Traits advertises none; duplicates and unknown traits are invalid. Callers must not mutate returned Traits concurrently with SDK use.

func DetectFeatures

func DetectFeatures(ctx context.Context, p Provider) (FeatureSet, error)

DetectFeatures derives real optional interfaces unless a configurable provider explicitly reports which of its transport traits are installed.

func (FeatureSet) Has

func (f FeatureSet) Has(trait Feature) bool

Has tests only the advertised trait list. It does not authorize an operation or replace scope-qualified catalog admission.

type GetRequest

type GetRequest struct {
	Route          AccessRoute       `json:"route"`
	Reference      ResourceReference `json:"reference"`
	Representation string            `json:"representation"`
}

GetRequest selects one reference through a route, with an explicit body format. Request containers are borrowed for the call; retaining or mutating them requires an independent copy.

func FromProtoGetRequest

func FromProtoGetRequest(p *resourcepb.GetInput) (GetRequest, error)

FromProtoGetRequest decodes an explicit route, reference, and representation without dispatch. It rejects nil or invalid messages; successful output owns mutable storage.

func (*GetRequest) UnmarshalJSON

func (v *GetRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes GetRequest, rejecting duplicate members, unknown fields, and invalid domain values.

type Getter

type Getter interface {
	Get(context.Context, GetRequest) (Record, error)
}

Getter supplies point reads only; it does not imply enumeration or live updates. Get must return the requested identity and admitted representation or an error.

Example
package main

import (
	"context"
	"fmt"

	resourcev2 "github.com/omniviewdev/plugin-sdk/pkg/resource/v2"
)

func exampleRepresentation() resourcev2.Representation {
	return resourcev2.Representation{
		ID:       "document",
		Revision: "1",
		Schema:   resourcev2.SchemaBinding{State: "absent", Validation: "none"},
	}
}

func exampleCatalog(context.Context, resourcev2.CatalogRequest) (resourcev2.Catalog, error) {
	representation := exampleRepresentation()
	return resourcev2.Catalog{
		Provider: "example", Revision: "metadata-1", Coverage: resourcev2.Coverage{Kind: "complete"},
		Types: []resourcev2.ResourceType{{
			Type: "document", DisplayName: "Document", Representations: []resourcev2.Representation{representation},
			DefaultRepresentation: representation.ID,
			Capabilities:          []resourcev2.Capability{{Operation: resourcev2.OperationGet}},
		}},
	}, nil
}

func main() {
	provider, err := resourcev2.NewController(resourcev2.Config[struct{}]{
		Catalog: exampleCatalog,
		Registrations: []resourcev2.Registration[struct{}]{{
			Type: "document",
			Get: func(ctx context.Context, _ *struct{}, request resourcev2.GetRequest) (resourcev2.Record, error) {
				return resourcev2.Record{
					Reference:      request.Reference,
					Body:           resourcev2.Value{Kind: "map", Map: map[string]resourcev2.Value{}},
					Representation: exampleRepresentation(),
					Coverage:       resourcev2.Coverage{Kind: "complete"},
				}, ctx.Err()
			},
		}},
	})
	if err != nil {
		panic(err)
	}
	defer provider.Close()
	route := resourcev2.AccessRoute{Connection: "profile"}
	catalog, err := provider.Catalog(context.Background(), resourcev2.CatalogRequest{Route: route})
	if err != nil {
		panic(err)
	}
	// A real host issues this authority after its own admission, not the provider.
	request := resourcev2.GetRequest{
		Route: route,
		Reference: resourcev2.ResourceReference{Address: resourcev2.ResourceAddress{
			Provider: "example", Authority: "host-issued", Type: "document", ID: "readme",
		}},
		Representation: exampleRepresentation().ID,
	}
	ctx := resourcev2.WithCatalogRevisionForRoute(context.Background(), catalog.Provider, route, catalog.Revision)
	record, err := provider.Get(ctx, request)
	fmt.Println(record.Reference.Address.ID, err)
}
Output:
readme <nil>

type HealthCondition

type HealthCondition struct {
	Type               string     `json:"type"`
	Status             string     `json:"status"`
	Reason             string     `json:"reason,omitempty"`
	Message            string     `json:"message,omitempty"`
	LastProbeTime      *time.Time `json:"lastProbeTime,omitempty"`
	LastTransitionTime *time.Time `json:"lastTransitionTime,omitempty"`
}

HealthCondition retains a provider-defined condition type and status without interpreting native condition vocabularies. Optional nil times are unknown, not the zero instant. Reason and Message must be safe for public display.

type HealthProvider

type HealthProvider interface {
	GetHealth(context.Context, GetRequest, Value) (*ResourceHealth, error)
	GetResourceEvents(context.Context, GetRequest, uint32) ([]ResourceEvent, error)
}

HealthProvider optionally derives health from the supplied resource body and fetches bounded native resource events. Neither method implies Getter support, network connection health, or advisory watch continuity.

GetHealth may return nil, nil when no health value is available. A nil event slice is empty; acquisition failures must return errors. A positive event limit bounds returned count; zero does not remove the SDK's finite event ceiling. Calls may run concurrently: honor cancellation, synchronize shared state, and do not mutate borrowed body containers. Return stable results and public-safe errors as described by Provider.

type HealthStatus

type HealthStatus string

HealthStatus describes observed resource health, not connection readiness. Unknown is explicit uncertainty; the zero string is not a health observation.

const (
	// HealthHealthy reports normal observed resource health.
	HealthHealthy HealthStatus = "healthy"
	// HealthDegraded reports impaired but not wholly failed resource health.
	HealthDegraded HealthStatus = "degraded"
	// HealthUnhealthy reports failed resource health.
	HealthUnhealthy HealthStatus = "unhealthy"
	// HealthPending reports health assessment or establishment still in progress.
	HealthPending HealthStatus = "pending"
	// HealthUnknown explicitly reports insufficient evidence to assess health.
	HealthUnknown HealthStatus = "unknown"
)

type Lifecycle

type Lifecycle[ClientT any] struct {
	LoadConnections func(context.Context) ([]types.Connection, error)
	CreateClient    func(context.Context, types.Connection) (*ClientT, error)
	DestroyClient   func(context.Context, *ClientT) error
	CheckConnection func(context.Context, types.Connection, *ClientT) (types.ConnectionStatus, error)
	OnStart         func(context.Context, types.Connection, *ClientT) error
	OnStop          func(context.Context, types.Connection, *ClientT) error
}

Lifecycle owns configured profiles and native client generations. When supplied, LoadConnections, CreateClient, and DestroyClient are required; other hooks are optional. Discovery does not start clients. Connection arguments are independent configuration snapshots, not writable registry state.

CreateClient receives a generation context: the initiating request can cancel startup until construction finishes, but a successful start outlives that request. Stop, reconfiguration, Close, or startup failure cancel the generation. A nil client with nil error is invalid. Every returned nonnil client is destroyed exactly once, including clients returned with an error or rejected by OnStart.

OnStart must finish before leases become usable. Retirement cancels the generation, stops watches, and drains leases before OnStop and DestroyClient. Cleanup contexts retain values but not the retired context's cancellation or deadline; cleanup must terminate without waiting for that cancellation. Hooks may run concurrently for different connections and with discovery. Do not synchronously reenter inventory mutation from teardown hooks, or acquire work on the generation being started or destroyed.

Nil CheckConnection reports local lifecycle state only, not network health. A supplied check must return a status bound to the requested connection. Hooks do not negotiate live resources, watches, or other optional traits.

Example
package main

import (
	"context"
	"fmt"

	resourcev2 "github.com/omniviewdev/plugin-sdk/pkg/resource/v2"
	"github.com/omniviewdev/plugin-sdk/pkg/types"
)

func exampleRepresentation() resourcev2.Representation {
	return resourcev2.Representation{
		ID:       "document",
		Revision: "1",
		Schema:   resourcev2.SchemaBinding{State: "absent", Validation: "none"},
	}
}

func exampleCatalog(context.Context, resourcev2.CatalogRequest) (resourcev2.Catalog, error) {
	representation := exampleRepresentation()
	return resourcev2.Catalog{
		Provider: "example", Revision: "metadata-1", Coverage: resourcev2.Coverage{Kind: "complete"},
		Types: []resourcev2.ResourceType{{
			Type: "document", DisplayName: "Document", Representations: []resourcev2.Representation{representation},
			DefaultRepresentation: representation.ID,
			Capabilities:          []resourcev2.Capability{{Operation: resourcev2.OperationGet}},
		}},
	}, nil
}

// exampleClient stands for the provider's native SDK client.
type exampleClient struct{ closed bool }

func main() {
	provider, err := resourcev2.NewController(resourcev2.Config[exampleClient]{
		Catalog: exampleCatalog,
		Lifecycle: &resourcev2.Lifecycle[exampleClient]{
			LoadConnections: func(context.Context) ([]types.Connection, error) {
				return []types.Connection{{ID: "profile", Name: "Example"}}, nil
			},
			CreateClient: func(ctx context.Context, _ types.Connection) (*exampleClient, error) {
				// Real constructors use ctx and profile for native acquisition.
				return &exampleClient{}, ctx.Err()
			},
			DestroyClient: func(_ context.Context, client *exampleClient) error {
				client.closed = true
				return nil
			},
		},
	})
	if err != nil {
		panic(err)
	}
	defer provider.Close()
	ctx := context.Background()
	if _, loadErr := provider.LoadConnections(ctx); loadErr != nil {
		panic(loadErr)
	}
	if _, startErr := provider.StartConnection(ctx, "profile"); startErr != nil {
		panic(startErr)
	}
	err = provider.WithConnection(
		ctx,
		resourcev2.AccessRoute{Connection: "profile"},
		func(_ context.Context, profile types.Connection) error {
			fmt.Println(profile.ID)
			return nil
		},
	)
	if err != nil {
		panic(err)
	}
	if _, err := provider.StopConnection(ctx, "profile"); err != nil {
		panic(err)
	}
}
Output:
profile

type MutationRequest

type MutationRequest struct {
	Route     AccessRoute       `json:"route"`
	Reference ResourceReference `json:"reference"`
	Operation string            `json:"operation"`
	Input     Value             `json:"input"`
	// ExpectedRevision optionally carries a native optimistic-write observation;
	// nil requests no such precondition. It is not a catalog admission pin.
	ExpectedRevision *string `json:"expectedRevision,omitempty"`
}

MutationRequest selects create, update, or delete. Catalog admission maps update to OperationMutationUpdate, never to the advisory OperationUpdate. Its mutable input is borrowed for the call, not transferred to the provider.

func FromProtoMutationRequest

func FromProtoMutationRequest(p *resourcepb.MutationInput) (MutationRequest, error)

FromProtoMutationRequest decodes mutation intent and expected revision without authorization or execution. It rejects nil or invalid messages; successful output owns mutable storage.

func (*MutationRequest) UnmarshalJSON

func (v *MutationRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes MutationRequest, rejecting duplicate members, unknown fields, and invalid domain values.

type Mutator

type Mutator interface {
	Mutate(context.Context, MutationRequest) (Record, error)
}

Mutator is optional. Each supported verb still needs its own scope-qualified catalog capability; implementing this interface does not imply CRUD support.

type NativeAuthorityHint

type NativeAuthorityHint struct {
	Scheme     string `json:"scheme"`
	ID         string `json:"id"`
	Continuity string `json:"continuity"`
}

NativeAuthorityHint is nonauthoritative provider metadata. Only the host may issue AuthorityID or decide sharing. Equal hints never establish permission.

func (*NativeAuthorityHint) UnmarshalJSON

func (v *NativeAuthorityHint) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes NativeAuthorityHint, rejecting duplicate members, unknown fields, and invalid domain values.

type NativeQuerier

type NativeQuerier interface {
	NativeQuery(context.Context, NativeQueryRequest) (SourcePage, error)
}

NativeQuerier is independent of Enumerator. Native query support still requires a matching scoped catalog capability and explicit representation provenance.

type NativeQueryDescriptor

type NativeQueryDescriptor struct {
	Language    string `json:"language"`
	Description string `json:"description,omitempty"`
	InputSchema Schema `json:"inputSchema"`
}

NativeQueryDescriptor declares one provider-native language and its object input. It does not grant query capability or change source-page semantics.

func (*NativeQueryDescriptor) UnmarshalJSON

func (v *NativeQueryDescriptor) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects duplicate fields and unsupported descriptor fields.

type NativeQueryRequest

type NativeQueryRequest struct {
	Target   ReadTarget `json:"target"`
	Language string     `json:"language"`
	Query    Value      `json:"query"`
	PageSize uint32     `json:"pageSize"`
	Cursor   *string    `json:"cursor,omitempty"`
}

NativeQueryRequest passes an explicitly named native query language and typed query value. Native query interpretation never broadens the admitted Target. Cursor has the same source-local lifetime as EnumerateRequest.Cursor.

func FromProtoNativeQueryRequest

func FromProtoNativeQueryRequest(p *resourcepb.NativeQueryInput) (NativeQueryRequest, error)

FromProtoNativeQueryRequest decodes an opaque native query and target without executing it. It rejects nil or invalid messages; successful output owns mutable storage.

func (*NativeQueryRequest) UnmarshalJSON

func (v *NativeQueryRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes NativeQueryRequest, rejecting duplicate members, unknown fields, and invalid domain values.

type Operation

type Operation string

Operation names independently admitted capabilities, not required methods. Advertising one operation never implies support for another.

const (
	// OperationEnumerate advertises scoped native enumeration, not final host query membership.
	OperationEnumerate Operation = "enumerate"
	// OperationGet advertises acquisition of one exact canonical reference.
	OperationGet Operation = "get"
	// OperationNativeQuery advertises provider-native query execution.
	OperationNativeQuery Operation = "nativeQuery"
	// OperationUpdate describes advisory watch delivery, not mutation.
	OperationUpdate Operation = "update"
	// OperationCreate admits only the create mutation verb.
	OperationCreate Operation = "create"
	// OperationMutationUpdate admits only the update mutation verb, never advisory delivery.
	OperationMutationUpdate Operation = "mutationUpdate"
	// OperationDelete admits only the delete mutation verb.
	OperationDelete Operation = "delete"
	// OperationAction advertises action dispatch; action descriptors define available actions.
	OperationAction Operation = "action"
)

type PresentationProvider

type PresentationProvider interface {
	GetResourceGroups(context.Context, AccessRoute) ([]ResourceGroup, error)
	GetResourceDefinition(context.Context, AccessRoute, string) (ResourceDefinition, error)
}

PresentationProvider supplies optional grouping and display metadata for an explicit route and type. It does not advertise finite resource capabilities or replace the canonical catalog. Empty groups may be returned as a nil slice; failure to acquire metadata must be an error, not fabricated empty success. Calls may run concurrently. Honor cancellation and return stable, independently owned containers; errors follow Provider's public-safe contract.

type Provider

type Provider interface {
	Catalog(context.Context, CatalogRequest) (Catalog, error)
}

Provider requires only connection-qualified catalog discovery. Finite operations and connection lifecycle are independent optional interfaces. Calls may overlap, including across connections. Implementations must observe caller cancellation and synchronize shared native state. Request containers are borrowed read-only for each call; copy before retaining them. Result containers must remain stable for caller use, not be recycled across calls. On error, callers discard the accompanying result. Zero-value catalogs, pages, records, and Values are not substitutes for a successful empty result.

Example
package main

import (
	"context"
	"fmt"

	resourcev2 "github.com/omniviewdev/plugin-sdk/pkg/resource/v2"
)

// A catalog-only provider needs no client, CRUD methods, or update source.
type catalogOnly struct{}

func (catalogOnly) Catalog(ctx context.Context, request resourcev2.CatalogRequest) (resourcev2.Catalog, error) {
	if err := ctx.Err(); err != nil {
		return resourcev2.Catalog{}, err
	}
	if request.Route.Connection == "" {
		return resourcev2.Catalog{}, resourcev2.NewError("INVALID_REQUEST", "Select a connection.")
	}
	return resourcev2.Catalog{
		Provider: "example",
		Revision: "metadata-1",
		Coverage: resourcev2.Coverage{Kind: "complete"},
	}, nil
}

func main() {
	var provider resourcev2.Provider = catalogOnly{}
	catalog, err := provider.Catalog(
		context.Background(),
		resourcev2.CatalogRequest{Route: resourcev2.AccessRoute{Connection: "profile"}},
	)
	fmt.Println(catalog.Provider, err)
}
Output:
example <nil>

type QueryScope

type QueryScope []ScopeConstraint

QueryScope intersects constraints across dimensions. Each declared query dimension must appear exactly once, including unrestricted dimensions. Nil or empty scope therefore applies only to a type with no query dimensions; it does not mean all dimensions. Constraint and selection order is immaterial. JSON requires a nonnull array; Go nil scopes serialize as an empty array.

func ScopeForAddress

func ScopeForAddress(address ResourceAddress, descriptor ResourceType) (QueryScope, error)

ScopeForAddress projects validated identity onto declared query dimensions. Selection-only dimensions remain explicit any/unknown. This is support qualification only: callers must independently admit trusted access covering that entire derived scope and must never infer a narrower native selection.

func (QueryScope) MarshalJSON

func (v QueryScope) MarshalJSON() ([]byte, error)

MarshalJSON validates QueryScope and emits canonical JSON without mutating caller-owned containers.

func (*QueryScope) UnmarshalJSON

func (v *QueryScope) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes QueryScope, rejecting duplicate members, unknown fields, and invalid domain values.

type ReadTarget

type ReadTarget struct {
	Route          AccessRoute `json:"route"`
	Provider       string      `json:"provider"`
	Authority      string      `json:"authority"`
	Type           string      `json:"type"`
	Scope          QueryScope  `json:"scope"`
	Representation string      `json:"representation"`
}

ReadTarget binds a scoped acquisition to an explicit route and host authority. Representation must already be resolved from catalog metadata; empty is invalid. Scope selects query dimensions, not merely the dimensions present in identity.

func CanonicalReadTarget

func CanonicalReadTarget(target ReadTarget) (ReadTarget, string, error)

CanonicalReadTarget validates a target and returns an independently owned, normalized snapshot plus its deterministic domain fingerprint. Scope order and repeated oneOf values do not affect the fingerprint. Route, provider, authority, type, representation, and every scope selection do affect it.

The fingerprint is an in-process equality key, not a durable wire format, source revision, authorization grant, or query-continuity token. The caller may mutate the returned snapshot without changing the input; recompute its fingerprint before using a changed snapshot as an acquisition key.

func FromProtoReadTarget

func FromProtoReadTarget(p *resourcepb.ReadTarget) (ReadTarget, error)

FromProtoReadTarget decodes route-qualified scope without catalog admission. It rejects nil or invalid messages; successful output owns mutable storage.

func MatchRelationshipTarget

func MatchRelationshipTarget(
	req RelationshipResolutionRequest,
	route AccessRoute,
	provider, typ string,
	scope []ScopeEntry,
) (ReadTarget, error)

MatchRelationshipTarget selects exactly one host binding for an observed link. Neither source identity nor a provider default can supply a missing binding.

func (*ReadTarget) UnmarshalJSON

func (v *ReadTarget) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes ReadTarget, rejecting duplicate members, unknown fields, and invalid domain values.

type Record

type Record struct {
	Reference      ResourceReference `json:"reference"`
	Body           Value             `json:"body"`
	Representation Representation    `json:"representation"`
	Coverage       Coverage          `json:"coverage"`
	// SourceRevision optionally observes native content state. Nil makes no
	// revision claim; a token is opaque and is neither identity nor incarnation.
	SourceRevision *string `json:"sourceRevision,omitempty"`
}

Record carries one map-root body with explicit identity, representation, and coverage provenance. Return independently owned mutable containers; do not reuse backing maps, slices, or schema bytes while a caller may consume them.

func FromProtoRecord

func FromProtoRecord(p *resourcepb.Record) (Record, error)

FromProtoRecord decodes body, representation, coverage, and source revision independently. It rejects nil or invalid messages; successful output owns mutable storage.

func (*Record) UnmarshalJSON

func (v *Record) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Record, rejecting duplicate members, unknown fields, and invalid domain values.

type Registration

type Registration[ClientT any] struct {
	Type        string
	Connection  string
	Scope       QueryScope
	Get         func(context.Context, *ClientT, GetRequest) (Record, error)
	Enumerate   func(context.Context, *ClientT, EnumerateRequest) (SourcePage, error)
	NativeQuery func(context.Context, *ClientT, NativeQueryRequest) (SourcePage, error)
	Mutate      func(context.Context, *ClientT, MutationRequest) (Record, error)
	Action      func(context.Context, *ClientT, ActionRequest) (Value, error)
	// Actions declares the finite actions handled by Action, including schemas.
	Actions []ActionDescriptor
	// Watch supplies advisory best-effort updates, never P05 continuity.
	Watch           func(context.Context, *ClientT, ReadTarget, Representation, WatchEventSink) error
	SyncPolicy      SyncPolicy
	ErrorClassifier ErrorClassifier
}

Registration binds independently optional callbacks to an exact resource type. Empty Connection permits any explicitly supplied route, never a default. Nil Scope adds no restriction to catalog admission; a nonnil Scope narrows it. Overlapping registrations for the same operation are rejected at dispatch. A callback alone does not advertise support: the catalog must independently declare that operation and scope. Mutate handles only admitted create, update, or delete declarations; Watch never implies finite read or mutation support.

Callbacks share a leased native client and can run concurrently. Their contexts end when the request, controller, or generation ends; do not retain the client beyond callback return or synchronously retire its generation. Observe cancellation so retirement can drain. With no Lifecycle, the client is nil. Finite request containers are borrowed during the call; do not mutate them concurrently. Return results that remain stable while SDK validation and transport consume them. Watch targets and representation containers are copied independently from retained admission; its sink remains framework-owned.

type RelationshipDescriptor

type RelationshipDescriptor struct {
	Type         RelationshipType `json:"type"`
	TargetType   string           `json:"targetType"`
	Label        string           `json:"label"`
	InverseLabel string           `json:"inverseLabel,omitempty"`
	Cardinality  string           `json:"cardinality,omitempty"`
	Direction    EdgeDirection    `json:"direction,omitempty"`
	// Nil Extractor leaves native resolution to the provider; it is not an
	// instruction for the host to scan for matching resources.
	Extractor *RelationshipExtractor `json:"extractor,omitempty"`
	// TargetScope contains literal dimensions; ScopeExtractors derive the rest.
	// A dimension must not occur in both or repeat within either collection.
	TargetScope     []ScopeEntry     `json:"targetScope"`
	ScopeExtractors []ScopeExtractor `json:"scopeExtractors"`
}

RelationshipDescriptor combines observed-link extraction and presentation. It does not admit a target route, imply enumeration support, or prove that every possible link has been resolved.

func FromProtoRelationshipDescriptor

func FromProtoRelationshipDescriptor(p *resourcepb.RelationshipDescriptor) (RelationshipDescriptor, error)

FromProtoRelationshipDescriptor decodes relationship metadata and validated extractor JSON without resolving targets. It rejects nil or invalid messages; successful output owns mutable storage.

type RelationshipExtractor

type RelationshipExtractor struct {
	Method        string            `json:"method"`
	FieldPath     string            `json:"fieldPath,omitempty"`
	LabelSelector map[string]string `json:"labelSelector,omitempty"`
}

RelationshipExtractor describes how native link evidence is found. Native labels and field values cannot supply target authority or replace host bindings.

type RelationshipProvider

type RelationshipProvider interface {
	GetRelationships(context.Context, AccessRoute, string) ([]RelationshipDescriptor, error)
	ResolveRelationships(context.Context, RelationshipResolutionRequest) ([]ResolvedRelationship, error)
}

RelationshipProvider declares optional relationships and resolves explicitly supplied source and target contexts. Resolution must honor each selected route, authority, scope, and accepted catalog observation; a source observation does not authorize a different target route. Results must remain inside the request bindings checked by ValidateRelationshipResolutionResult.

Nil descriptor/result slices are empty results, not acquisition failures. Calls may overlap: honor cancellation, synchronize shared state, and keep borrowed inputs and returned containers stable during SDK use. Errors follow Provider's public-safe contract.

type RelationshipResolutionRequest

type RelationshipResolutionRequest struct {
	Source GetRequest `json:"source"`
	// Targets may be empty to admit no links. Each target Scope must be nonnil,
	// even when its declared query space has no dimensions.
	Targets []ReadTarget `json:"targets"`
}

RelationshipResolutionRequest supplies explicit host-admitted target bindings for observed native links. Bindings are not permission grants and never authorize enumeration or scans. The provider must not reuse source authority for a different target or fabricate a missing binding; unsupported/unresolved links fail explicitly rather than silently becoming complete empty results. Target bindings must have explicit scopes and must not overlap for the same provider, type, and route. Such bindings must share query dimension sets. Returned references must preserve binding authority and cover every binding query dimension; additional identity dimensions remain part of the reference. An empty target list admits no links. JSON admission rejects unknown or duplicate members and null arrays. Targets and their nested scope/value slices are borrowed for resolution; copy them before retaining or changing them. Results must own mutable containers independently and must not silently drop links outside an explicit binding.

func FromProtoRelationshipResolutionRequest

func FromProtoRelationshipResolutionRequest(
	p *resourcepb.RelationshipResolutionInput,
) (RelationshipResolutionRequest, error)

FromProtoRelationshipResolutionRequest decodes source and explicit target bindings without admitting their catalog observations. It rejects nil or invalid messages; successful output owns mutable storage.

func (RelationshipResolutionRequest) MarshalJSON

func (v RelationshipResolutionRequest) MarshalJSON() ([]byte, error)

MarshalJSON validates bindings and encodes an empty target set as an array, never null.

func (*RelationshipResolutionRequest) UnmarshalJSON

func (v *RelationshipResolutionRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON admits explicit source and target bindings. It rejects unknown fields and duplicate members before decoding.

type RelationshipTarget

type RelationshipTarget struct {
	Reference   ResourceReference `json:"reference"`
	Route       AccessRoute       `json:"route"`
	DisplayName string            `json:"displayName,omitempty"`
}

RelationshipTarget carries independently bound target identity and access. Route must come from an explicit matching host binding, not source authority.

type RelationshipType

type RelationshipType string

RelationshipType describes the semantic link; it does not authorize following that link or accessing its target.

const (
	// RelOwns links an owner to an owned resource.
	RelOwns RelationshipType = "owns"
	// RelRunsOn links a workload to its execution resource.
	RelRunsOn RelationshipType = "runs_on"
	// RelUses links a consumer to a dependency.
	RelUses RelationshipType = "uses"
	// RelExposes links an exposing resource to the resource it makes accessible.
	RelExposes RelationshipType = "exposes"
	// RelManages links a manager to a managed resource.
	RelManages RelationshipType = "manages"
	// RelMemberOf links a member to its containing group.
	RelMemberOf RelationshipType = "member_of"
	// RelSelects links a selector to a matching resource.
	RelSelects RelationshipType = "selects"
)

type Representation

type Representation struct {
	ID       string        `json:"id"`
	Revision string        `json:"revision"`
	Schema   SchemaBinding `json:"schema"`
}

Representation declares a body format and its schema observation. Revision tracks that format's contract, independently of record or catalog revisions.

func (*Representation) UnmarshalJSON

func (v *Representation) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Representation, rejecting duplicate members, unknown fields, and invalid domain values.

type ResolvedRelationship

type ResolvedRelationship struct {
	Descriptor RelationshipDescriptor `json:"descriptor"`
	Targets    []RelationshipTarget   `json:"targets"`
}

ResolvedRelationship returns concrete observed links under one descriptor. Empty Targets cannot stand in for unsupported resolution or a missing binding. Result slices and nested descriptor containers must remain stable for callers.

func FromProtoResolvedRelationship

func FromProtoResolvedRelationship(p *resourcepb.ResolvedRelationship) (ResolvedRelationship, error)

FromProtoResolvedRelationship decodes a descriptor and explicit targets without cross-route admission. It rejects nil or invalid messages; successful output owns mutable storage.

type ResourceAddress

type ResourceAddress struct {
	Provider  string `json:"provider"`
	Authority string `json:"authority"`
	Type      string `json:"type"`
	// Scope contains each declared identity dimension exactly once. Order does
	// not affect identity; no entries means the type has no identity dimensions.
	Scope []ScopeEntry `json:"scope"`
	ID    string       `json:"id"`
}

ResourceAddress identifies an object independently of the connection used to access it. Type and ID are opaque; callers must not parse native syntax from them. Authority is host-issued, not a provider's native authority hint.

func (ResourceAddress) MarshalJSON

func (v ResourceAddress) MarshalJSON() ([]byte, error)

MarshalJSON validates ResourceAddress and emits canonical JSON without mutating caller-owned containers.

func (*ResourceAddress) UnmarshalJSON

func (v *ResourceAddress) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes ResourceAddress, rejecting duplicate members, unknown fields, and invalid domain values.

type ResourceDefinition

type ResourceDefinition struct {
	ColumnDefs []ColumnDefinition `json:"columnDefs"`
}

ResourceDefinition supplies display columns without changing record bodies. Return stable column slices and nested metadata rather than mutable shared buffers.

type ResourceEvent

type ResourceEvent struct {
	Type      EventSeverity `json:"type"`
	Reason    string        `json:"reason"`
	Message   string        `json:"message"`
	Source    string        `json:"source,omitempty"`
	Count     int32         `json:"count,omitempty"`
	FirstSeen time.Time     `json:"firstSeen"`
	LastSeen  time.Time     `json:"lastSeen"`
}

ResourceEvent is a diagnostic observation, not advisory add/update/delete delivery or a continuity log. Count cannot be negative and LastSeen must not precede FirstSeen. Reason, Message, and Source must be safe for public display.

func FromProtoResourceEvent

func FromProtoResourceEvent(p *resourcepb.ResourceEvent) (ResourceEvent, error)

FromProtoResourceEvent decodes event severity and timestamps without establishing replay continuity. It rejects nil or invalid messages; successful output owns mutable storage.

type ResourceGroup

type ResourceGroup struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Icon        string   `json:"icon"`
	Resources   []string `json:"resources"`
}

ResourceGroup organizes opaque resource type IDs for presentation. Group membership does not add capabilities or change identity and authority.

type ResourceHealth

type ResourceHealth struct {
	Status     HealthStatus      `json:"status"`
	Reason     string            `json:"reason,omitempty"`
	Message    string            `json:"message,omitempty"`
	Since      *time.Time        `json:"since,omitempty"`
	Conditions []HealthCondition `json:"conditions,omitempty"`
}

ResourceHealth is a health observation, independent of lifecycle registration and finite-operation support. Nil Since means no transition time was supplied; an empty Conditions slice does not establish healthy status.

func FromProtoResourceHealth

func FromProtoResourceHealth(p *resourcepb.ResourceHealth) (ResourceHealth, error)

FromProtoResourceHealth decodes health conditions and observation times without probing native health. It rejects nil or invalid messages; successful output owns mutable storage.

type ResourceLink struct {
	// Type is a literal canonical type. Otherwise TypeAccessor and an explicit
	// TypeMap translate observed native values; the two selection forms conflict.
	Type           string            `json:"type,omitempty"`
	TypeAccessor   string            `json:"typeAccessor,omitempty"`
	TypeMap        map[string]string `json:"typeMap,omitempty"`
	IDAccessor     string            `json:"idAccessor"`
	ScopeAccessors []ScopeExtractor  `json:"scopeAccessors"`
	DisplayID      bool              `json:"displayId"`
}

ResourceLink is a presentation extractor. Resolved identity is always a ResourceReference; access routes are supplied independently by the host.

type ResourceMetadata

type ResourceMetadata struct {
	Labels    map[string]string `json:"labels,omitempty"`
	CreatedAt *time.Time        `json:"createdAt,omitempty"`
}

ResourceMetadata carries optional display metadata outside canonical identity and body provenance. Nil CreatedAt means no creation time was supplied.

type ResourceOperationError

type ResourceOperationError struct {
	Err         error    `json:"-"`
	Code        string   `json:"code"`
	Title       string   `json:"title"`
	Message     string   `json:"message"`
	Suggestions []string `json:"suggestions,omitempty"`
}

ResourceOperationError preserves provider classification across the resource transport. Title, Message, and Suggestions must contain public-safe text: never include credentials, private configuration, or raw native diagnostics. Put native diagnostics in Err, which is excluded from JSON and exposed only through Unwrap. Error serializes classification and public text, not Err. The host still owns redaction, canonical AppError provenance, and recovery policy; provider text and classification never grant permission.

func (*ResourceOperationError) Error

func (e *ResourceOperationError) Error() string

Error returns JSON containing public classification and presentation only. A nil receiver returns an INTERNAL classification without native diagnostics.

func (*ResourceOperationError) Unwrap

func (e *ResourceOperationError) Unwrap() error

Unwrap exposes the native cause for local inspection; a nil receiver has no cause.

type ResourceReference

type ResourceReference struct {
	Address     ResourceAddress `json:"address"`
	Incarnation *string         `json:"incarnation,omitempty"`
}

ResourceReference adds an optional native incarnation observation to identity. A nil Incarnation makes no claim about object recreation; it is not a source revision or an access route.

func FromProtoResourceReference

func FromProtoResourceReference(p *resourcepb.ResourceReference) (ResourceReference, error)

FromProtoResourceReference decodes canonical identity and optional incarnation without selecting access. It rejects nil or invalid messages; successful output owns mutable storage.

func (*ResourceReference) UnmarshalJSON

func (v *ResourceReference) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes ResourceReference, rejecting duplicate members, unknown fields, and invalid domain values.

type ResourceType

type ResourceType struct {
	Type               string           `json:"type"`
	DisplayName        string           `json:"displayName"`
	IdentityDimensions []Dimension      `json:"identityDimensions"`
	QueryDimensions    []Dimension      `json:"queryDimensions"`
	Representations    []Representation `json:"representations"`
	// DefaultRepresentation is optional catalog selection metadata, not an
	// implicit provider default. When set it must name a declared representation.
	DefaultRepresentation string `json:"defaultRepresentation,omitempty"`
	// ModelRepresentation optionally selects a provider projection for model consumers.
	// It never changes DefaultRepresentation or grants operation capability.
	ModelRepresentation string                  `json:"modelRepresentation,omitempty"`
	NativeQueries       []NativeQueryDescriptor `json:"nativeQueries,omitempty"`
	Capabilities        []Capability            `json:"capabilities"`
	NativeAuthorityHint *NativeAuthorityHint    `json:"nativeAuthorityHint,omitempty"`
}

ResourceType declares identity, query space, formats, and independent support. Query-only dimensions cannot be inferred from an object's identity scope.

func AdmitBestEffortTarget

func AdmitBestEffortTarget(
	ctx context.Context,
	provider Provider,
	target ReadTarget,
) (descriptor ResourceType, err error)

AdmitBestEffortTarget checks the independently optional advisory update interface and its exact catalog scope. It makes no P05 continuity promise. A nonnil provider/context and accepted route catalog observation are required. It calls Catalog without starting a source or retaining a lease; callers must separately fence native startup, retries, and delivery. It grants no authority.

func AdmitCatalogOperation

func AdmitCatalogOperation(catalog Catalog, request any) (ResourceType, error)

AdmitCatalogOperation uses an already acquired catalog without another discovery RPC. A ReadTarget requests advisory update capability admission. It validates domain request values against declared support only; it neither checks a provider's optional Go traits nor an accepted/current revision pair. No native work, lasting lease, or access authorization occurs. Keep catalog containers stable while using the returned descriptor, which can share them.

func AdmitOperation

func AdmitOperation(ctx context.Context, provider Provider, request any) (descriptor ResourceType, err error)

AdmitOperation is shared by controller and transport admission. Direct providers must declare the route/type/scope and implement the optional method. Requests are domain values, not generated transport messages or pointers. Use a nonnil provider and context. Finite request values, not pointers, are accepted; unsupported shapes or missing optional traits return UNSUPPORTED. This calls Catalog and requires the exact accepted route observation. It does not invoke the operation, retain a lease after return, or authorize the caller. Providers/callers must still fence dispatch and results against retirement.

func AdmitStreamingAction

func AdmitStreamingAction(
	ctx context.Context,
	provider Provider,
	request ActionRequest,
) (descriptor ResourceType, err error)

AdmitStreamingAction admits the independent streaming action interface without requiring a finite Action method or fabricating finite action support. It requires a nonnil provider/context and an accepted route catalog observation. It calls Catalog but not StreamAction, acquires no lasting lease, and grants no authority. Admission success cannot replace a result or generation fence.

func (ResourceType) MarshalJSON

func (v ResourceType) MarshalJSON() ([]byte, error)

MarshalJSON validates ResourceType and emits canonical JSON without mutating caller-owned containers.

func (*ResourceType) UnmarshalJSON

func (v *ResourceType) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes ResourceType, rejecting duplicate members, unknown fields, and invalid domain values.

type Schema

type Schema struct {
	Properties map[string]SchemaProperty `json:"properties,omitempty"`
	Required   []string                  `json:"required,omitempty"`
}

Schema is the retained action-schema convenience subset. It is not P07's normalized resource schema and does not claim support for omitted constraints.

func (Schema) MarshalJSON

func (s Schema) MarshalJSON() ([]byte, error)

MarshalJSON emits the object-root action-schema subset without applying defaults.

func (Schema) Ptr

func (s Schema) Ptr() *Schema

Ptr returns a shallow pointer copy; nested maps and slices remain shared with s.

func (*Schema) UnmarshalJSON

func (s *Schema) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects malformed or duplicate JSON, unsupported constraints, unknown fields, and non-object roots. It replaces s only after validation.

type SchemaBinding

type SchemaBinding struct {
	State    string  `json:"state"`
	Revision *string `json:"revision,omitempty"`
	Dialect  string  `json:"dialect,omitempty"`
	// Root is a local RFC6901 URI-fragment pointer; empty selects the whole
	// document. Resolving it never implies external document acquisition.
	Root        string                   `json:"root,omitempty"`
	DocumentRef *SchemaDocumentReference `json:"documentRef,omitempty"`
	Document    json.RawMessage          `json:"document,omitempty"`
	// Validation is full, reduced, or none. Reduced requires explicit
	// Unvalidated constraints; full and none forbid such claims.
	Validation  string   `json:"validation"`
	Unvalidated []string `json:"unvalidated"`
	// UnavailableReason is an optional reviewed ErrorCode, not native diagnostic
	// text, and is valid only in the unavailable state.
	UnavailableReason *string `json:"unavailableReason,omitempty"`
}

SchemaBinding distinguishes known absence from failed schema acquisition. Available schemas require a revision, dialect, and exactly one inline Document or DocumentRef. Absent schemas have no document binding. Unavailable schemas cannot carry inline documents and must not be reported as absent. Revisions are opaque equality observations, never object identity.

func (SchemaBinding) MarshalJSON

func (v SchemaBinding) MarshalJSON() ([]byte, error)

MarshalJSON validates SchemaBinding and emits canonical JSON without mutating caller-owned containers.

func (*SchemaBinding) UnmarshalJSON

func (v *SchemaBinding) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes SchemaBinding, rejecting duplicate members, unknown fields, and invalid domain values.

type SchemaDocument

type SchemaDocument struct {
	Reference SchemaDocumentReference `json:"reference"`
	Dialect   string                  `json:"dialect"`
	Document  json.RawMessage         `json:"document"`
}

SchemaDocument is a bounded raw schema shared by reference across bindings. Document is not normalized; its mutable bytes must remain stable during use.

func FromProtoSchemaDocument

func FromProtoSchemaDocument(p *resourcepb.SchemaDocument) (SchemaDocument, error)

FromProtoSchemaDocument decodes schema bytes and reference without resolving external documents. It rejects nil or invalid messages; successful output owns mutable storage.

func (*SchemaDocument) UnmarshalJSON

func (v *SchemaDocument) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes SchemaDocument, rejecting duplicate members, unknown fields, and invalid domain values.

type SchemaDocumentProvider

type SchemaDocumentProvider interface {
	GetSchemaDocument(context.Context, AccessRoute, SchemaDocumentReference) (SchemaDocument, error)
}

SchemaDocumentProvider resolves an explicit schema-document reference without implicit external loading or normalization by the SDK. The returned document must retain the exact requested reference. Return acquisition errors rather than a zero document; public error text must not disclose private source URLs or diagnostics. Calls may run concurrently; honor cancellation and return independently owned, stable document containers.

type SchemaDocumentReference

type SchemaDocumentReference struct {
	ID       string `json:"id"`
	Revision string `json:"revision"`
}

SchemaDocumentReference shares one bounded raw document across catalog roots.

func FromProtoSchemaDocumentReference

func FromProtoSchemaDocumentReference(p *resourcepb.SchemaDocumentReference) (SchemaDocumentReference, error)

FromProtoSchemaDocumentReference decodes an opaque schema document identity and revision without fetching it. It rejects nil or invalid messages; successful output owns mutable storage.

func (*SchemaDocumentReference) UnmarshalJSON

func (v *SchemaDocumentReference) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes SchemaDocumentReference, rejecting duplicate members, unknown fields, and invalid domain values.

type SchemaProperty

type SchemaProperty struct {
	Type        SchemaType `json:"type"`
	Description string     `json:"description,omitempty"`
	Enum        []string   `json:"enum,omitempty"`
	// Nil bounds are absent; pointers to zero express an actual numeric bound.
	Minimum    *float64                  `json:"minimum,omitempty"`
	Maximum    *float64                  `json:"maximum,omitempty"`
	Properties map[string]SchemaProperty `json:"properties,omitempty"`
	Required   []string                  `json:"required,omitempty"`
}

SchemaProperty describes only the supported ancillary constraints. Defaults and coercion are unsupported; arrays do not constrain their elements.

func (SchemaProperty) MarshalJSON

func (p SchemaProperty) MarshalJSON() ([]byte, error)

MarshalJSON emits bounds as exact decimal values of their binary float64 representation, so strict decoders never round a schema during transport.

func (*SchemaProperty) UnmarshalJSON

func (p *SchemaProperty) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects duplicate fields and constraints outside this subset. A default keyword is unsupported even when its value is null.

type SchemaType

type SchemaType string

SchemaType names a primitive in the action-schema subset, not a resource representation or an exhaustive schema dialect.

const (
	// SchemaString describes textual action input without coercion.
	SchemaString SchemaType = "string"
	// SchemaInteger describes integral action input.
	SchemaInteger SchemaType = "integer"
	// SchemaNumber describes numeric action input, including nonintegral values.
	SchemaNumber SchemaType = "number"
	// SchemaBoolean describes true-or-false action input.
	SchemaBoolean SchemaType = "boolean"
	// SchemaObject describes named nested properties.
	SchemaObject SchemaType = "object"
	// SchemaArray describes a list-valued property.
	SchemaArray SchemaType = "array"
)

type ScopeConstraint

type ScopeConstraint struct {
	Dimension string     `json:"dimension"`
	Match     ScopeMatch `json:"match"`
	// Values must be nil for any and nonnil for oneOf. A nonnil empty selection
	// matches nothing; it must never be widened to any.
	Values *[]string `json:"values,omitempty"`
}

ScopeConstraint selects values within one declared query dimension.

func (ScopeConstraint) MarshalJSON

func (v ScopeConstraint) MarshalJSON() ([]byte, error)

MarshalJSON validates ScopeConstraint and emits canonical JSON without mutating caller-owned containers.

func (*ScopeConstraint) UnmarshalJSON

func (v *ScopeConstraint) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes ScopeConstraint, rejecting duplicate members, unknown fields, and invalid domain values.

type ScopeEntry

type ScopeEntry struct {
	Dimension string `json:"dimension"`
	Value     string `json:"value"`
}

ScopeEntry is one literal identity dimension, not a query constraint. Empty Value is meaningful only when the declared dimension permits it.

func (*ScopeEntry) UnmarshalJSON

func (v *ScopeEntry) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes ScopeEntry, rejecting duplicate members, unknown fields, and invalid domain values.

type ScopeExtractor

type ScopeExtractor struct {
	Dimension string `json:"dimension"`
	FieldPath string `json:"fieldPath"`
}

ScopeExtractor explicitly derives a target scope dimension from source data. TargetScope entries remain literal values; no accessor-string heuristics apply.

type ScopeMatch

type ScopeMatch string

ScopeMatch chooses unrestricted matching or an explicit finite selection for one dimension. A zero value is invalid, not an implicit wildcard.

const (
	// ScopeAny selects every value of one declared query dimension.
	ScopeAny ScopeMatch = "any"
	// ScopeOneOf selects exactly Values; an empty selection matches nothing.
	ScopeOneOf ScopeMatch = "oneOf"
)

type ScopeValuesProvider

type ScopeValuesProvider interface {
	ScopeValues(context.Context, AccessRoute, string) ([]string, error)
}

ScopeValuesProvider optionally discovers values for a named query dimension on an explicit route. Discovery does not authorize or constrain acquisition; catalogs and request admission remain authoritative. Namespaces are one Kubernetes dimension, never a universal requirement.

A nil slice is an empty discovery result, not a wildcard or failure. Calls may overlap other provider work: honor cancellation, synchronize shared state, and return stable result containers. Errors follow Provider's public-safe contract.

type Session

type Session struct {
	Connection   *types.Connection
	PluginConfig pkgsettings.Provider
	RequestID    string
	RequesterID  string
	PluginID     string
	Values       map[string]any
}

Session holds diagnostic and route context. RequesterID is never a grant. Connection may be nil when no profile is selected. Values and PluginConfig are borrowed references, not immutable snapshots or SDK-enforced synchronization.

func SessionFromContext

func SessionFromContext(ctx context.Context) (Session, bool)

SessionFromContext returns the stored session and whether one exists. Its pointer, map, and provider members retain the ownership passed to WithSession.

type SourcePage

type SourcePage struct {
	Records []Record `json:"records"`
	// NextCursor is nil when no continuation is offered. Nonempty tokens retain
	// native source semantics, not portable host-query or continuity semantics.
	NextCursor *string  `json:"nextCursor,omitempty"`
	Count      Count    `json:"count"`
	Coverage   Coverage `json:"coverage"`
	// Consistency is bestEffort or pointInTime. Neither establishes an atomic
	// transition from this finite page to advisory updates.
	Consistency    string  `json:"consistency"`
	SourceRevision *string `json:"sourceRevision,omitempty"`
}

SourcePage is a bounded acquisition page, never a final host query page. Empty Records alone does not establish complete coverage or a zero total. Providers must preserve explicit coverage and consistency even for empty pages.

func FromProtoSourcePage

func FromProtoSourcePage(p *resourcepb.SourcePage) (SourcePage, error)

FromProtoSourcePage decodes records, coverage, exact count intent, and opaque cursor independently. It rejects nil or invalid messages; successful output owns mutable storage.

func (SourcePage) MarshalJSON

func (v SourcePage) MarshalJSON() ([]byte, error)

MarshalJSON validates SourcePage and emits canonical JSON without mutating caller-owned containers.

func (*SourcePage) UnmarshalJSON

func (v *SourcePage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes SourcePage, rejecting duplicate members, unknown fields, and invalid domain values.

type StreamingActioner

type StreamingActioner interface {
	StreamAction(context.Context, ActionRequest, chan<- ActionEvent) error
}

StreamingActioner supplies independently optional action execution with native readiness. The framework owns the output channel and completion; producers send events and return, never close the channel. Emit exactly one ready event after native establishment and before output, progress, or completion. Establishment failure returns an error without ready; success without ready is invalid.

Honor cancellation for establishment, event sends, and teardown. Calls may run concurrently; synchronize shared state and do not mutate request or event containers while the framework consumes them. Return public-safe errors. A streaming implementation does not require Actioner, but still requires exact action catalog admission. Remote callers negotiate FeatureStreamingActions; a transport client's static Go method set alone is not evidence of support.

type SyncPolicy

type SyncPolicy int

SyncPolicy selects controller advisory-source startup, independently of finite read support. The zero policy is SyncOnConnect, not disabled updates.

const (
	// SyncOnConnect starts only the explicit targets passed to StartConnectionWatch.
	SyncOnConnect SyncPolicy = iota
	// SyncOnFirstQuery starts eligible sources on finite read demand.
	SyncOnFirstQuery
	// SyncNever disables explicit EnsureResourceWatch as well as automatic startup.
	SyncNever
)

type TypeActionTarget

type TypeActionTarget struct {
	Provider  string     `json:"provider"`
	Authority string     `json:"authority"`
	Type      string     `json:"type"`
	Scope     QueryScope `json:"scope"`
}

TypeActionTarget selects a resource type without inventing an object identity. Authority is host-issued; Scope selects declared query dimensions.

func (*TypeActionTarget) UnmarshalJSON

func (v *TypeActionTarget) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects unknown or duplicate type-target members.

type Value

type Value struct {
	Kind      string           `json:"kind"`
	Bool      bool             `json:"-"`
	String    string           `json:"-"`
	Int       string           `json:"-"`
	Uint      string           `json:"-"`
	Double    float64          `json:"-"`
	Timestamp string           `json:"-"`
	List      []Value          `json:"-"`
	Map       map[string]Value `json:"-"`
}

Value preserves scalar intent rather than reducing every number to float64. Kind is null, bool, string, int64, uint64, double, timestamp, list, or map; the zero Value is invalid. Only the selected payload may be populated. Int and Uint use canonical decimal strings within their respective 64-bit ranges. Double must be finite and preserves negative zero. Timestamp uses UTC RFC3339 with nanosecond precision. A selected nil List or Map is an empty container, not null. Nested containers remain mutable: copy them before retaining borrowed input or sharing values with code that may mutate them.

func FromProtoValue

func FromProtoValue(p *resourcepb.Value) (Value, error)

FromProtoValue decodes canonical scalar kinds and exact integer values. It rejects nil or invalid messages; successful output owns mutable storage.

func JSONToValue

func JSONToValue(data []byte) (Value, error)

JSONToValue admits a native JSON resource document. Integral tokens retain exact signed/unsigned intent; only fractional/exponent tokens become doubles. Native JSON strings never acquire timestamp intent.

func TimestampValue

func TimestampValue(t time.Time) Value

TimestampValue constructs an exact timestamp without floating-point seconds.

func ValueFromNative

func ValueFromNative(raw any) (Value, error)

ValueFromNative preserves native scalar types without a JSON float roundtrip. Unsupported native types fail rather than stringify or silently lose intent.

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

MarshalJSON emits deterministic tagged JSON, preserving integers, timestamps, and negative zero. Both semantic value budgets and raw tagged-JSON budgets apply before allocation.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(data []byte) error

UnmarshalJSON admits the strict tagged encoding without changing the receiver on failure. Duplicate members, malformed Unicode, and missing or inactive payloads are rejected.

type WatchAddPayload

type WatchAddPayload struct {
	Route     AccessRoute      `json:"route"`
	Record    Record           `json:"record"`
	Metadata  ResourceMetadata `json:"metadata"`
	Guarantee string           `json:"guarantee"`
}

WatchAddPayload reports an advisory observed addition, not proof that the object did not previously exist. Record retains the admitted identity and representation.

func FromProtoWatchAddPayload

func FromProtoWatchAddPayload(p *resourcepb.WatchAddPayload) (WatchAddPayload, error)

FromProtoWatchAddPayload decodes advisory ADD data without establishing listener readiness or continuity. It rejects nil or invalid messages; successful output owns mutable storage.

type WatchConnectionSummary

type WatchConnectionSummary struct {
	Route          AccessRoute           `json:"route"`
	Resources      map[string]WatchState `json:"resources"`
	ResourceCounts map[string]Count      `json:"resourceCounts"`
	// Scope is optional summary metadata, not permission to widen individual
	// admitted targets. Nil does not establish unrestricted acquisition.
	Scope     QueryScope `json:"scope"`
	Guarantee string     `json:"guarantee"`
}

WatchConnectionSummary is a source-state observation, not a total inventory. Resources and ResourceCounts are keyed by opaque resource type; unknown counts must not be treated as zero or inferred from the number of map entries.

func FromProtoWatchConnectionSummary

func FromProtoWatchConnectionSummary(p *resourcepb.WatchConnectionSummary) (WatchConnectionSummary, error)

FromProtoWatchConnectionSummary decodes per-type advisory states and counts without starting watches. It rejects nil or invalid messages; successful output owns mutable storage.

type WatchDeletePayload

type WatchDeletePayload struct {
	Route     AccessRoute       `json:"route"`
	Reference ResourceReference `json:"reference"`
	LastKnown *Record           `json:"lastKnown,omitempty"`
	Guarantee string            `json:"guarantee"`
}

WatchDeletePayload identifies the observed deletion without requiring a body. Nil LastKnown means no prior record is available; it is not an empty record. When supplied, LastKnown must agree with Reference and admitted representation.

func FromProtoWatchDeletePayload

func FromProtoWatchDeletePayload(p *resourcepb.WatchDeletePayload) (WatchDeletePayload, error)

FromProtoWatchDeletePayload decodes advisory DELETE identity and optional last-known record without replay guarantees. It rejects nil or invalid messages; successful output owns mutable storage.

type WatchEventSink

type WatchEventSink interface {
	OnAdd(WatchAddPayload)
	OnUpdate(WatchUpdatePayload)
	OnDelete(WatchDeletePayload)
	OnStateChange(WatchStateEvent)
}

WatchEventSink receives borrowed advisory payloads. Callbacks may overlap; synchronize sink state and treat nested payload containers as read-only. Copy mutable data before retaining or editing it. Blocking callbacks delay source delivery and listener retirement; no callback may outlive listener return.

type WatchState

type WatchState int

WatchState describes one advisory source's lifecycle, not connection health or source completeness. In particular, synced cannot prove gap-free delivery.

const (
	// WatchStateIdle means the source is registered but has not begun syncing.
	WatchStateIdle WatchState = iota
	// WatchStateSyncing means native cache acquisition is in progress.
	WatchStateSyncing
	// WatchStateSynced means the native cache reports readiness, not continuity.
	WatchStateSynced
	// WatchStateError means an attempt failed and may be retried.
	WatchStateError
	// WatchStateStopped means the source ended without a terminal failure.
	WatchStateStopped
	// WatchStateFailed means the source exhausted retries or failed admission.
	WatchStateFailed
	// WatchStateForbidden means source access was denied.
	WatchStateForbidden
	// WatchStateSkipped means startup was intentionally omitted.
	WatchStateSkipped
)

type WatchStateEvent

type WatchStateEvent struct {
	Route     AccessRoute             `json:"route"`
	Type      string                  `json:"type"`
	State     WatchState              `json:"state"`
	Count     Count                   `json:"count"`
	Error     *ResourceOperationError `json:"error,omitempty"`
	Message   string                  `json:"message,omitempty"`
	Guarantee string                  `json:"guarantee"`
}

WatchStateEvent reports advisory source state. WatchStateSynced means native cache readiness only, not a point-in-time snapshot or a gap-free stream. Count describes observed cache membership, never total native cardinality. Message and Error must contain public-safe text, not raw native diagnostics.

func FromProtoWatchStateEvent

func FromProtoWatchStateEvent(p *resourcepb.WatchStateEvent) (WatchStateEvent, error)

FromProtoWatchStateEvent decodes advisory source state without changing source lifecycle. It rejects nil or invalid messages; successful output owns mutable storage.

type WatchUpdatePayload

type WatchUpdatePayload struct {
	Route     AccessRoute      `json:"route"`
	Record    Record           `json:"record"`
	Metadata  ResourceMetadata `json:"metadata"`
	Guarantee string           `json:"guarantee"`
}

WatchUpdatePayload carries a full canonical record, not an implicit patch. Missing earlier events cannot be detected or recovered from this payload alone.

func FromProtoWatchUpdatePayload

func FromProtoWatchUpdatePayload(p *resourcepb.WatchUpdatePayload) (WatchUpdatePayload, error)

FromProtoWatchUpdatePayload decodes advisory UPDATE data without establishing listener readiness or continuity. It rejects nil or invalid messages; successful output owns mutable storage.

Directories

Path Synopsis
Package plugin transports resource v2 providers over bounded, validated gRPC messages.
Package plugin transports resource v2 providers over bounded, validated gRPC messages.

Jump to

Keyboard shortcuts

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