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; OperationSourceUpdates declares source-session continuity. AcquireOnConnect retains explicit provider policy for supported consumers, not universal eager inventory. Controller is optional; it owns one native-client registry and leases. 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.
CatalogRequest observes installed support by default. Refresh explicitly asks for eligible discovery; schema acquisition is never catalog readiness work. Representation contains only body-format ID and revision for finite and source records. SchemaResolver optionally resolves one exact SchemaRequest target. Public SchemaDocumentRequest qualifies an exact reference with its target; SchemaDocumentProvider remains the trusted held-reference lookup. Initial source admission keeps the exact accepted observation. Ongoing fences retain the original native epoch and selected operational contract, not global catalog revisions, unrelated support, or presentation/schema observations.
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.
Providers may opt into a shared acquisition-timeout preference by registering ConnectionAcquisitionTimeoutSetting and resolving ConnectionAcquisitionTimeout once at each initial acquisition or catalog refresh. Apply the duration with context.WithTimeout to that work, not the retained client's generation context. The setting accepts 1-300 whole seconds, defaults to 10, and takes effect on the next acquisition. Earlier caller cancellation/deadlines still win. This policy does not schedule requests or know any provider's protocol.
Public connection facts ¶
Config.ConnectionMetadata optionally observes public server facts with an already-started client. Use namespaced keys such as "example.server_version". Return success observations with UTC timestamps, unavailable observations with safe errors, and explicit removals. Omitted keys retain their previous state. Never publish credentials, raw native errors, connection configuration, resource inventory, or derived summaries. Sanitize endpoint userinfo, queries, and fragments. The SDK detaches values, validates the complete atomic update, and owns revisions, freshness, generation fences, and bounded snapshot streams. Get never acquires; Refresh never connects. Discovery invalidations must use Controller.InvalidateConnectionMetadata rather than independently publish cache observations. Concurrent refreshes share work, while invalidations coalesce one follow-up pass. Stop cancels acquisition and revokes publication before teardown. Consumers negotiate FeatureConnectionMetadata, subscribe before fetching, compare revisions numerically within a provider registration, and treat transport loss as unknown rather than current proof. Metadata does not grant authorization.
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 ¶
- Constants
- func BindCatalogRevision(bindingEpoch, nativeRevision string) (string, error)
- func CatalogBindingEpoch(revision string) (string, error)
- func CatalogRevisionForRouteFromContext(ctx context.Context, provider string, route AccessRoute) (string, bool)
- func CatalogRevisionFromContext(ctx context.Context) (string, bool)
- func CheckCatalogRevision(ctx context.Context, catalog Catalog) error
- func CheckCatalogRevisionForRoute(ctx context.Context, catalog Catalog, route AccessRoute) error
- func CheckSourceCatalog(ctx context.Context, catalog Catalog, request SourceOpenRequest, ...) error
- func CloneConnection(connection types.Connection) types.Connection
- func ConnectionAcquisitionTimeout(ctx context.Context) (time.Duration, error)
- func ConnectionAcquisitionTimeoutSetting() settings.Setting
- func ErrorCode(err error) string
- func IsErrorCode(code string) bool
- func NativeFromValue(v Value) (any, error)
- func NewCatalogBindingEpoch() (string, error)
- func NewError(code, detail string) error
- func PtrFloat64(v float64) *float64
- func QualifiedCatalogRevisionFromContext(ctx context.Context, provider string, route AccessRoute) (string, bool)
- func RecordWireSize(r Record) (int, error)
- func SameConnectionClientConfig(a, b types.Connection) bool
- func SourceChangesWireSize(changes SourceChanges) (int, error)
- func SourceGuaranteeForTarget(descriptor ResourceType, target ReadTarget) string
- func SourceObservationWireSize(observation SourceObservation) (int, error)
- func SourceOperationalContractEqual(previous, current ResourceType, request SourceOpenRequest) bool
- func SourcePageResponseWireSize(payloadBytes int) int
- func SourcePageWireCost(page SourcePage) (payloadBytes, nodes, fields int, err error)
- func SourceRecordWireCost(record Record) (payloadBytes, nodes, fields int, err error)
- func ToProtoAccessRoute(v AccessRoute) (*resourcepb.AccessRoute, error)
- func ToProtoActionRequest(v ActionRequest) (*resourcepb.ActionInput, error)
- func ToProtoCatalog(v Catalog) (*resourcepb.Catalog, error)
- func ToProtoCatalogRequest(v CatalogRequest) (*resourcepb.CatalogRequest, error)
- func ToProtoEnumerateRequest(v EnumerateRequest) (*resourcepb.EnumerateInput, error)
- func ToProtoGetRequest(v GetRequest) (*resourcepb.GetInput, error)
- func ToProtoMutationRequest(v MutationRequest) (*resourcepb.MutationInput, error)
- func ToProtoNativeQueryRequest(v NativeQueryRequest) (*resourcepb.NativeQueryInput, error)
- func ToProtoQueryScope(v QueryScope) (*resourcepb.QueryScope, error)
- func ToProtoReadTarget(v ReadTarget) (*resourcepb.ReadTarget, error)
- func ToProtoRecord(v Record) (*resourcepb.Record, error)
- func ToProtoRelationshipDescriptor(v RelationshipDescriptor) (*resourcepb.RelationshipDescriptor, error)
- func ToProtoRelationshipResolutionRequest(v RelationshipResolutionRequest) (*resourcepb.RelationshipResolutionInput, error)
- func ToProtoResolvedRelationship(v ResolvedRelationship) (*resourcepb.ResolvedRelationship, error)
- func ToProtoResourceEvent(v ResourceEvent) (*resourcepb.ResourceEvent, error)
- func ToProtoResourceHealth(v ResourceHealth) (*resourcepb.ResourceHealth, error)
- func ToProtoResourceReference(v ResourceReference) (*resourcepb.ResourceReference, error)
- func ToProtoSchemaBinding(v SchemaBinding) (*resourcepb.SchemaBinding, error)
- func ToProtoSchemaDocument(v SchemaDocument) (*resourcepb.SchemaDocument, error)
- func ToProtoSchemaDocumentReference(v SchemaDocumentReference) (*resourcepb.SchemaDocumentReference, error)
- func ToProtoSchemaDocumentRequest(v SchemaDocumentRequest) (*resourcepb.SchemaDocumentRequest, error)
- func ToProtoSchemaRequest(v SchemaRequest) (*resourcepb.SchemaRequest, error)
- func ToProtoSourceAcquisition(v SourceAcquisition) (*resourcepb.SourceAcquisition, error)
- func ToProtoSourceBegin(v SourceBegin) (*resourcepb.SourceBegin, error)
- func ToProtoSourceChange(v SourceChange) (*resourcepb.SourceChange, error)
- func ToProtoSourceChanges(v SourceChanges) (*resourcepb.SourceChanges, error)
- func ToProtoSourceCoverage(v SourceCoverage) (*resourcepb.SourceCoverage, error)
- func ToProtoSourceFailure(v SourceFailure) (*resourcepb.SourceFailure, error)
- func ToProtoSourceFrame(v SourceFrame) (*resourcepb.SourceFrame, error)
- func ToProtoSourceLimits(v SourceLimits) (*resourcepb.SourceLimits, error)
- func ToProtoSourceObservation(v SourceObservation) (*resourcepb.SourceObservation, error)
- func ToProtoSourceOpenRequest(v SourceOpenRequest) (*resourcepb.SourceOpenRequest, error)
- func ToProtoSourcePage(v SourcePage) (*resourcepb.SourcePage, error)
- func ToProtoSourceReset(v SourceReset) (*resourcepb.SourceReset, error)
- func ToProtoSourceSnapshot(v SourceSnapshot) (*resourcepb.SourceSnapshot, error)
- func ToProtoSourceSnapshotEnd(v SourceSnapshotEnd) (*resourcepb.SourceSnapshotEnd, error)
- func ToProtoValue(v Value) (*resourcepb.Value, error)
- func ValidateActionDescriptorRequest(request ActionRequest, descriptor ActionDescriptor, streaming bool) error
- func ValidateActionDescriptors(v []ActionDescriptor) error
- func ValidateActionInput(d ActionDescriptor, v Value) error
- func ValidateActionOutput(d ActionDescriptor, v Value) error
- func ValidateActionRequest(v ActionRequest) error
- func ValidateActivityPresentation(p ActivityPresentation) error
- func ValidateAddress(a ResourceAddress, declared ...[]Dimension) error
- func ValidateCatalog(c Catalog) error
- func ValidateCatalogFeatures(c Catalog, features FeatureSet) error
- func ValidateCatalogRevision(revision string) error
- func ValidateConnectionMetadataSnapshot(snapshot ConnectionMetadataSnapshot) error
- func ValidateConnectionMetadataUpdate(update ConnectionMetadataUpdate) error
- func ValidateConnectionOverlay(overlay ConnectionOverlay) error
- func ValidateEnumerateRequest(v EnumerateRequest) error
- func ValidateFeatures(f FeatureSet) error
- func ValidateGetRequest(v GetRequest) error
- func ValidateJSON(data []byte) error
- func ValidateMetadata(v any) error
- func ValidateMutationRequest(v MutationRequest) error
- func ValidateNativeQueryInput(descriptor ResourceType, request NativeQueryRequest) error
- func ValidateNativeQueryRequest(v NativeQueryRequest) error
- func ValidateOperationResult(request any, result any, descriptor ResourceType) error
- func ValidateProviderCatalog(ctx context.Context, provider Provider, catalog Catalog) error
- func ValidateRecord(r Record) error
- func ValidateRelationshipResolutionRequest(req RelationshipResolutionRequest) error
- func ValidateRelationshipResolutionResult(req RelationshipResolutionRequest, results []ResolvedRelationship) error
- func ValidateResolvedActionOutput(descriptor *ActionDescriptor, value Value) error
- func ValidateResourceDefinition(v ResourceDefinition) error
- func ValidateResourceGroups(v []ResourceGroup) error
- func ValidateResourceOptionsJSON(data []byte) error
- func ValidateSchema(s Schema) error
- func ValidateSchemaBinding(s SchemaBinding) error
- func ValidateSchemaDocument(v SchemaDocument) error
- func ValidateSchemaDocumentRequest(v SchemaDocumentRequest) error
- func ValidateSchemaRequest(v SchemaRequest) error
- func ValidateSchemaUnavailableReason(reason string) error
- func ValidateSchemaValue(s Schema, v Value) error
- func ValidateScope(s QueryScope, declared ...[]Dimension) error
- func ValidateSourceObservation(target ReadTarget, representation string, observation SourceObservation) error
- func ValidateSourceOpenRequest(r SourceOpenRequest) error
- func ValidateSourcePage(p SourcePage) error
- func ValidateValue(v Value) error
- func ValueWireSize(v Value) (int, error)
- func WithCatalogRevision(ctx context.Context, revision string) context.Context
- func WithCatalogRevisionForRoute(ctx context.Context, provider string, route AccessRoute, revision string) context.Context
- func WithSession(ctx context.Context, session Session) context.Context
- func WithUtilityConnection(pc *types.PluginContext, provider ConnectionContextProvider, ...) error
- type AccessRoute
- type ActionCatalog
- type ActionDescriptor
- type ActionEvent
- type ActionRequest
- type ActionScope
- type Actioner
- type ActivityAction
- type ActivityMetric
- type ActivityPresentation
- type ActivityProgress
- type AuxiliarySchemaTarget
- type Capability
- type Catalog
- type CatalogRequest
- type Closer
- type ColumnDefinition
- type Config
- type ConnectionBrowser
- type ConnectionContextConsumer
- type ConnectionContextProvider
- type ConnectionLifecycle
- type ConnectionMetadataEntry
- type ConnectionMetadataError
- type ConnectionMetadataEvent
- type ConnectionMetadataObservation
- type ConnectionMetadataProvider
- type ConnectionMetadataSink
- type ConnectionMetadataSnapshot
- type ConnectionMetadataUpdate
- type ConnectionOverlay
- type ConnectionOverlayProvider
- type ConnectionReadinessProvider
- type Controller
- func (c *Controller[T]) Action(ctx context.Context, request ActionRequest) (value Value, err error)
- func (c *Controller[T]) ApplyConnectionOverlay(ctx context.Context, overlay ConnectionOverlay) error
- func (c *Controller[T]) ApplyConnections(ctx context.Context, connections []types.Connection) error
- func (c *Controller[T]) Catalog(ctx context.Context, request CatalogRequest) (catalog Catalog, err error)
- func (c *Controller[T]) CheckConnection(ctx context.Context, id string) (status types.ConnectionStatus, err error)
- func (c *Controller[T]) Close() error
- func (c *Controller[T]) DeleteConnection(ctx context.Context, id string) error
- func (c *Controller[T]) Enumerate(ctx context.Context, request EnumerateRequest) (page SourcePage, err error)
- func (c *Controller[T]) Features(ctx context.Context) (FeatureSet, error)
- func (c *Controller[T]) Get(ctx context.Context, request GetRequest) (record Record, err error)
- func (c *Controller[T]) GetActions(ctx context.Context, route AccessRoute, typ string) ([]ActionDescriptor, error)
- func (c *Controller[T]) GetConnection(ctx context.Context, id string) (types.Connection, error)
- func (c *Controller[T]) GetConnectionMetadata(ctx context.Context, id string) (ConnectionMetadataSnapshot, error)
- func (c *Controller[T]) GetConnectionStatus(ctx context.Context, id string) (types.ConnectionStatus, error)
- func (c *Controller[T]) InvalidateConnectionMetadata(ctx context.Context, id string) error
- func (c *Controller[T]) ListConnections(ctx context.Context) ([]types.Connection, error)
- func (c *Controller[T]) LoadConnections(ctx context.Context) (connections []types.Connection, err error)
- func (c *Controller[T]) Mutate(ctx context.Context, request MutationRequest) (record Record, err error)
- func (c *Controller[T]) NativeConnections(ctx context.Context) ([]types.Connection, error)
- func (c *Controller[T]) NativeQuery(ctx context.Context, request NativeQueryRequest) (page SourcePage, err error)
- func (c *Controller[T]) OpenSource(ctx context.Context, request SourceOpenRequest, emitter SourceEmitter) (err error)
- func (c *Controller[T]) RefreshConnectionMetadata(ctx context.Context, id string) (ConnectionMetadataSnapshot, error)
- func (c *Controller[T]) StartConnection(ctx context.Context, id string) (status types.ConnectionStatus, err error)
- func (c *Controller[T]) StopConnection(ctx context.Context, id string) (connection types.Connection, err error)
- func (c *Controller[T]) UpdateConnection(ctx context.Context, connection types.Connection) (types.Connection, error)
- func (c *Controller[T]) WatchConnectionMetadata(ctx context.Context, sink ConnectionMetadataSink) error
- func (c *Controller[T]) WithClient(ctx context.Context, route AccessRoute, fn func(context.Context, *T) error) (err error)
- func (c *Controller[T]) WithConnection(ctx context.Context, route AccessRoute, ...) (err error)
- type Count
- type Coverage
- type Dimension
- type DocumentCoverage
- type DocumentFieldPath
- type EdgeDirection
- type EnumerateRequest
- type Enumerator
- type ErrorClassifier
- type EventSeverity
- type Feature
- type FeatureNegotiator
- type FeatureSet
- type FieldPathSegment
- type GetRequest
- type Getter
- type HealthCondition
- type HealthProvider
- type HealthStatus
- type Lifecycle
- type MutationRequest
- type Mutator
- type NativeAuthorityHint
- type NativeQuerier
- type NativeQueryDescriptor
- type NativeQueryRequest
- type Operation
- type PresentationProvider
- type Provider
- type QueryScope
- type ReadTarget
- type Record
- type Registration
- type RelationshipDescriptor
- type RelationshipExtractor
- type RelationshipProvider
- type RelationshipResolutionRequest
- type RelationshipTarget
- type RelationshipType
- type Representation
- type RepresentationBinding
- type ResolvedRelationship
- type ResourceActionIntent
- type ResourceAddress
- type ResourceDefinition
- type ResourceEvent
- type ResourceGroup
- type ResourceHealth
- type ResourceLink
- type ResourceMetadata
- type ResourceNavigationIntent
- type ResourceOperationError
- type ResourceReference
- type ResourceType
- func AdmitCatalogOperation(catalog Catalog, request any) (ResourceType, error)
- func AdmitOperation(ctx context.Context, provider Provider, request any) (descriptor ResourceType, err error)
- func AdmitStreamingAction(ctx context.Context, provider Provider, request ActionRequest) (descriptor ResourceType, err error)
- type Schema
- type SchemaBinding
- type SchemaDocument
- type SchemaDocumentProvider
- type SchemaDocumentReference
- type SchemaDocumentRequest
- type SchemaProperty
- type SchemaRequest
- type SchemaResolver
- type SchemaTarget
- type SchemaType
- type ScopeConstraint
- type ScopeEntry
- type ScopeExtractor
- type ScopeMatch
- type ScopeValuesProvider
- type Session
- type SourceAcquisition
- type SourceBegin
- type SourceChange
- type SourceChanges
- type SourceCoverage
- type SourceEmitter
- type SourceFailure
- type SourceFrame
- type SourceLimits
- type SourceObservation
- type SourceOpenRequest
- type SourcePage
- type SourcePhaseTracker
- type SourceProvider
- type SourceRecord
- type SourceRequest
- type SourceReset
- type SourceSnapshot
- type SourceSnapshotEnd
- type SourceStream
- type SourceStreamOpener
- type StreamingActioner
- type TypeActionTarget
- type Value
Examples ¶
Constants ¶
const ( MaxConnectionMetadataKeyBytes = 256 MaxConnectionMetadataEntries = 128 MaxConnectionMetadataEntryBytes = 16 << 10 MaxConnectionMetadataDepth = 16 MaxConnectionMetadataSnapshotBytes = 256 << 10 MaxConnectionMetadataErrorCodeBytes = 128 MaxConnectionMetadataErrorMessageBytes = 1024 // Successful snapshots reserve space for SDK lifecycle failure publication. ConnectionMetadataLifecycleReserveBytes = 512 )
Connection metadata limits bound both admission and complete published snapshots.
const ( DialectJSONSchema202012 = "https://json-schema.org/draft/2020-12/schema" DialectJSONSchemaDraft07 = "http://json-schema.org/draft-07/schema#" DialectOpenAPI30 = "openapi-3.0" )
Schema dialect identifiers. SDK validation requires only a non-empty dialect; the host schema catalog decides which dialects it normalizes.
const ( // ContinuityConnectionLocal makes no identity continuity claim across connections. ContinuityConnectionLocal = "connectionLocal" // ContinuityStableNative claims native identity continuity; the host still assigns authority. ContinuityStableNative = "stableNative" )
const ( SourceModeSnapshot = "snapshot" SourceModeSnapshotAndUpdates = "snapshotAndUpdates" SourceAcquisitionEnumerate = "enumerate" SourceAcquisitionNativeQuery = "nativeQuery" EnumerationExhausted = "exhausted" EnumerationPartial = "partial" EnumerationUnknown = "unknown" ConsistencyPointInTime = "pointInTime" ConsistencyBestEffort = "bestEffort" ConsistencyUnknown = "unknown" ContinuityNotApplicable = "notApplicable" ContinuityGapFree = "gapFree" ContinuityBestEffort = "bestEffort" SourceResetContinuityLost = "continuityLost" SourceResetOverflow = "overflow" SourceResetBindingChanged = "bindingChanged" SourceResetSourceInvalidated = "sourceInvalidated" SourceChangeUpsert = "upsert" SourceChangeRemove = "remove" MaxSourceBatchItems = 256 MinSourceFrameBytes = 1 MaxSourceFrameBytes = 4 << 20 MaxSourceTokenBytes = 128 MaxSourceLimitations = 256 MaxSourceMessageBytes = 1024 )
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 // MaxProtoDepth allows each semantic map level's Value, MapValue and // ValueEntry messages, plus 16 messages for the enclosing RPC. Semantic // Value depth remains limited by MaxValueDepth. MaxProtoDepth = MaxValueDepth*3 + 16 MaxValueNodes = maxDomainNodes MaxWireFields = maxDomainFields MaxPageRecords = maxPageRecords MaxPageBodyBytes = MaxMessageBytes )
These finite ceilings apply independently of the host's predicate policy.
const ConnectionAcquisitionTimeoutSettingID = "connection_acquisition_timeout_seconds"
ConnectionAcquisitionTimeoutSettingID is an opt-in provider setting. It bounds initial connection acquisition and explicit catalog refresh, not live clients, watches, or unrelated resource operations.
const MaxActivityPresentationBytes = 131072
MaxActivityPresentationBytes bounds the JSON representation on every activity transport.
const MaxCatalogRevisionBytes = 4096
MaxCatalogRevisionBytes bounds trusted admission context and its wire encoding.
const MaxCatalogRevisionMetadataBytes = 32 * 1024
MaxCatalogRevisionMetadataBytes bounds all catalog admission metadata together.
const MaxRelationshipTargets = 256
MaxRelationshipTargets is the bounded implementation-candidate ceiling for explicit relationship bindings, independent of inventory cardinality.
const WireVersion uint32 = 3
WireVersion identifies the resource transport contract, not a catalog revision.
Variables ¶
This section is empty.
Functions ¶
func BindCatalogRevision ¶
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 ¶
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 ¶
CatalogRevisionFromContext returns the default observation and its presence. Presence does not validate syntax or authorize dispatch; route-qualified lookup is separate.
func CheckCatalogRevision ¶
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 CheckSourceCatalog ¶ added in v0.20.0
func CheckSourceCatalog(ctx context.Context, catalog Catalog, request SourceOpenRequest, admitted ResourceType) error
CheckSourceCatalog fences ongoing work against the originally admitted native generation and selected operational contract, not an unrelated catalog change. Unknown discovery cannot prove withdrawal or authorize unobserved support.
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 ConnectionAcquisitionTimeout ¶ added in v0.14.3
ConnectionAcquisitionTimeout resolves an acquisition's policy from its plugin session. Missing session/configuration or an unset value uses the documented default. Provider read failures and invalid values remain errors. Callers apply this duration to acquisition work only, never to a retained client lifetime. context.WithTimeout preserves any earlier caller deadline or cancellation.
func ConnectionAcquisitionTimeoutSetting ¶ added in v0.14.3
ConnectionAcquisitionTimeoutSetting exposes the common acquisition policy in a plugin's settings. Changes apply to the next acquisition; they never change an operation already in flight. Providers must explicitly register and consume it.
func ErrorCode ¶
ErrorCode finds a reviewed classification through wrapping. It maps cancellation and deadlines explicitly, nil to empty, and unknown errors to INTERNAL.
func IsErrorCode ¶
IsErrorCode accepts the existing C02 provider-classification vocabulary. Unknown peer/provider codes never widen the host's canonical error contract.
func NativeFromValue ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 SourceChangesWireSize ¶ added in v0.14.4
func SourceChangesWireSize(changes SourceChanges) (int, error)
SourceChangesWireSize reports the exact protobuf payload size before encoding.
func SourceGuaranteeForTarget ¶ added in v0.14.0
func SourceGuaranteeForTarget(descriptor ResourceType, target ReadTarget) string
SourceGuaranteeForTarget returns the first source-updates guarantee whose declared scope contains the target scope, matching operation admission. It returns an empty string when no capability matches.
func SourceObservationWireSize ¶ added in v0.14.4
func SourceObservationWireSize(observation SourceObservation) (int, error)
SourceObservationWireSize reports protobuf bytes without materializing a wire tree.
func SourceOperationalContractEqual ¶ added in v0.20.0
func SourceOperationalContractEqual(previous, current ResourceType, request SourceOpenRequest) bool
SourceOperationalContractEqual compares only the selected source contract. Both descriptors and the selected request must already be admitted. Provider, route, principal, and generation admission remain independently required. Presentation, unrelated support, and global revisions do not own the source.
func SourcePageResponseWireSize ¶ added in v0.15.0
SourcePageResponseWireSize reports the complete Response size from the sum of page payload bytes, including the page envelope and record contributions.
func SourcePageWireCost ¶ added in v0.15.0
func SourcePageWireCost(page SourcePage) (payloadBytes, nodes, fields int, err error)
SourcePageWireCost reports the page payload bytes and the complete Response node and field counts, including page metadata, cursor, and response wrapper. Use an empty Records slice to compute the envelope for incremental assembly.
func SourceRecordWireCost ¶ added in v0.15.0
SourceRecordWireCost reports a finite Record's incremental contribution to the page payload bytes and Response node and field counts.
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.CatalogRequest, error)
ToProtoCatalogRequest preserves explicit refresh intent and route selection. 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 ToProtoQueryScope ¶ added in v0.13.0
func ToProtoQueryScope(v QueryScope) (*resourcepb.QueryScope, error)
ToProtoQueryScope validates and encodes a query scope.
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 ToProtoSchemaBinding ¶ added in v0.20.0
func ToProtoSchemaBinding(v SchemaBinding) (*resourcepb.SchemaBinding, error)
ToProtoSchemaBinding validates availability, document selection, and safe codes. It performs no document resolution and owns all 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 ToProtoSchemaDocumentRequest ¶ added in v0.20.0
func ToProtoSchemaDocumentRequest(v SchemaDocumentRequest) (*resourcepb.SchemaDocumentRequest, error)
ToProtoSchemaDocumentRequest encodes a target-qualified exact document lookup. It validates before encoding and owns all output storage.
func ToProtoSchemaRequest ¶ added in v0.20.0
func ToProtoSchemaRequest(v SchemaRequest) (*resourcepb.SchemaRequest, error)
ToProtoSchemaRequest validates and encodes one explicit schema target. It performs no schema acquisition and owns all output storage.
func ToProtoSourceAcquisition ¶ added in v0.14.0
func ToProtoSourceAcquisition(v SourceAcquisition) (*resourcepb.SourceAcquisition, error)
func ToProtoSourceBegin ¶ added in v0.14.0
func ToProtoSourceBegin(v SourceBegin) (*resourcepb.SourceBegin, error)
func ToProtoSourceChange ¶ added in v0.14.0
func ToProtoSourceChange(v SourceChange) (*resourcepb.SourceChange, error)
func ToProtoSourceChanges ¶ added in v0.14.0
func ToProtoSourceChanges(v SourceChanges) (*resourcepb.SourceChanges, error)
func ToProtoSourceCoverage ¶ added in v0.14.0
func ToProtoSourceCoverage(v SourceCoverage) (*resourcepb.SourceCoverage, error)
func ToProtoSourceFailure ¶ added in v0.14.0
func ToProtoSourceFailure(v SourceFailure) (*resourcepb.SourceFailure, error)
func ToProtoSourceFrame ¶ added in v0.14.0
func ToProtoSourceFrame(v SourceFrame) (*resourcepb.SourceFrame, error)
func ToProtoSourceLimits ¶ added in v0.14.0
func ToProtoSourceLimits(v SourceLimits) (*resourcepb.SourceLimits, error)
func ToProtoSourceObservation ¶ added in v0.14.0
func ToProtoSourceObservation(v SourceObservation) (*resourcepb.SourceObservation, error)
func ToProtoSourceOpenRequest ¶ added in v0.14.0
func ToProtoSourceOpenRequest(v SourceOpenRequest) (*resourcepb.SourceOpenRequest, error)
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 ToProtoSourceReset ¶ added in v0.14.0
func ToProtoSourceReset(v SourceReset) (*resourcepb.SourceReset, error)
func ToProtoSourceSnapshot ¶ added in v0.14.0
func ToProtoSourceSnapshot(v SourceSnapshot) (*resourcepb.SourceSnapshot, error)
func ToProtoSourceSnapshotEnd ¶ added in v0.14.0
func ToProtoSourceSnapshotEnd(v SourceSnapshotEnd) (*resourcepb.SourceSnapshotEnd, error)
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 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 ValidateActivityPresentation ¶ added in v0.15.0
func ValidateActivityPresentation(p ActivityPresentation) error
ValidateActivityPresentation checks presentation without interpreting business output.
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 ¶
ValidateCatalog checks type, body-format, and scoped capability declarations. It validates structure, not caller authorization or live source availability.
func ValidateCatalogFeatures ¶ added in v0.14.4
func ValidateCatalogFeatures(c Catalog, features FeatureSet) error
ValidateCatalogFeatures validates declarations in the context of negotiated provider features. Legacy updates remain inert and are valid only without source sessions.
func ValidateCatalogRevision ¶
ValidateCatalogRevision checks bounded observation syntax, not authorization.
func ValidateConnectionMetadataSnapshot ¶ added in v0.10.0
func ValidateConnectionMetadataSnapshot(snapshot ConnectionMetadataSnapshot) error
ValidateConnectionMetadataSnapshot validates complete state, including the final aggregate size after incremental updates. It never rewrites caller-owned data.
func ValidateConnectionMetadataUpdate ¶ added in v0.10.0
func ValidateConnectionMetadataUpdate(update ConnectionMetadataUpdate) error
ValidateConnectionMetadataUpdate admits an entire bounded patch without mutation. The coordinator must also validate the resulting complete snapshot before commit.
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, conflicting, or unknown trait names. Unknown traits return UNSUPPORTED; malformed declarations 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 ¶
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 ¶
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 ValidateProviderCatalog ¶ added in v0.14.4
ValidateProviderCatalog checks a catalog against its provider's reported features.
func ValidateRecord ¶
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 ValidateResourceOptionsJSON ¶ added in v0.15.0
ValidateResourceOptionsJSON validates option envelopes containing a tagged resource_data Value. Other fields retain the ordinary JSON depth limit.
func ValidateSchema ¶
ValidateSchema checks the restricted object-root ancillary schema. Defaults, coercion, item schemas, and other JSON Schema keywords are unsupported.
func ValidateSchemaBinding ¶ added in v0.20.0
func ValidateSchemaBinding(s SchemaBinding) error
ValidateSchemaBinding checks an optional schema observation without fetching documents.
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 ValidateSchemaDocumentRequest ¶ added in v0.20.0
func ValidateSchemaDocumentRequest(v SchemaDocumentRequest) error
ValidateSchemaDocumentRequest validates a target-qualified exact document lookup. Current access and the target's resolved reference remain caller-owned.
func ValidateSchemaRequest ¶ added in v0.20.0
func ValidateSchemaRequest(v SchemaRequest) error
ValidateSchemaRequest validates a bounded, explicitly selected schema target. It does not authorize access or resolve a current catalog/default selection.
func ValidateSchemaUnavailableReason ¶
ValidateSchemaUnavailableReason admits only bounded, safe machine codes. It never transports provider messages, URLs, credentials or diagnostics.
func ValidateSchemaValue ¶
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 ValidateSourceObservation ¶ added in v0.14.0
func ValidateSourceObservation(target ReadTarget, representation string, observation SourceObservation) error
ValidateSourceObservation validates a record and binds it to the requested target.
func ValidateSourceOpenRequest ¶ added in v0.14.0
func ValidateSourceOpenRequest(r SourceOpenRequest) error
ValidateSourceOpenRequest checks the request's target, acquisition and negotiated limits.
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 ¶
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 ¶
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 ¶
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 ¶
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"`
Activity *ActivityPresentation `json:"activity,omitempty"`
}
ActionEvent carries native readiness or subsequent action output. Emit exactly one ready before progress/output; output requires Data, while progress may carry Data, Activity, or both. 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 or Activity after sending or close caller-owned channels; observe cancellation while sending and return to complete.
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 ActivityAction ¶ added in v0.15.0
type ActivityAction struct {
ID string `json:"id"`
Kind string `json:"kind"`
Label string `json:"label"`
Target *ResourceNavigationIntent `json:"target,omitempty"`
Intent *ResourceActionIntent `json:"intent,omitempty"`
TaskID string `json:"taskId,omitempty"`
}
type ActivityMetric ¶ added in v0.15.0
type ActivityPresentation ¶ added in v0.15.0
type ActivityPresentation struct {
Title string `json:"title"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
Progress *ActivityProgress `json:"progress,omitempty"`
Metrics []ActivityMetric `json:"metrics,omitempty"`
Actions []ActivityAction `json:"actions,omitempty"`
}
ActivityPresentation is safe, data-only presentation independent of business output.
type ActivityProgress ¶ added in v0.15.0
type AuxiliarySchemaTarget ¶ added in v0.20.0
type AuxiliarySchemaTarget struct {
Key string `json:"key"`
Reference ResourceReference `json:"reference"`
SourceRevision *string `json:"sourceRevision,omitempty"`
}
AuxiliarySchemaTarget identifies one schema role on one exact resource. SourceRevision, when present, is a nonempty opaque equality observation. Neither the key nor a document reference grants access to another resource.
func (AuxiliarySchemaTarget) MarshalJSON ¶ added in v0.20.0
func (v AuxiliarySchemaTarget) MarshalJSON() ([]byte, error)
MarshalJSON validates the auxiliary identity without changing its observation.
func (*AuxiliarySchemaTarget) UnmarshalJSON ¶ added in v0.20.0
func (v *AuxiliarySchemaTarget) UnmarshalJSON(data []byte) error
UnmarshalJSON admits one exact auxiliary reference and optional source revision.
type Capability ¶
type Capability struct {
Operation Operation `json:"operation"`
Scope QueryScope `json:"scope"`
// Guarantee declares source update continuity; finite operations leave it empty.
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 ¶
MarshalJSON validates Catalog and emits canonical JSON without mutating caller-owned containers.
func (*Catalog) UnmarshalJSON ¶
UnmarshalJSON decodes Catalog, rejecting duplicate members, unknown fields, and invalid domain values.
type CatalogRequest ¶
type CatalogRequest struct {
Route AccessRoute `json:"route"`
Refresh bool `json:"refresh"`
}
CatalogRequest observes support through one explicit access route. Refresh requests eligible native discovery; ordinary observation performs no native discovery or schema acquisition and never starts a connection.
func FromProtoCatalogRequest ¶
func FromProtoCatalogRequest(p *resourcepb.CatalogRequest) (CatalogRequest, error)
FromProtoCatalogRequest decodes observation or explicit discovery refresh. 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] // ConnectionMetadata observes public server facts using an already-started // leased client. It must honor cancellation and never return secrets. ConnectionMetadata func(context.Context, types.Connection, *ClientT) (ConnectionMetadataUpdate, error) // 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) // DynamicSources declares that ResolveRegistration installs source callbacks. // Each target still requires catalog and callback admission. DynamicSources 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 ConnectionMetadataEntry ¶ added in v0.10.0
type ConnectionMetadataEntry struct {
State string `json:"state"`
Value any `json:"value"`
ObservedAt *time.Time `json:"observedAt,omitempty"`
Error *ConnectionMetadataError `json:"error,omitempty"`
}
ConnectionMetadataEntry is current, stale, or unavailable. Current and stale entries always serialize value, including null, false, zero, and empty strings. Unavailable entries omit value and observedAt and require a public-safe error.
func (ConnectionMetadataEntry) MarshalJSON ¶ added in v0.10.0
func (entry ConnectionMetadataEntry) MarshalJSON() ([]byte, error)
MarshalJSON preserves every successful value, including explicit JSON null.
func (*ConnectionMetadataEntry) UnmarshalJSON ¶ added in v0.10.0
func (entry *ConnectionMetadataEntry) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects unknown, duplicate, missing, and invalid union fields.
type ConnectionMetadataError ¶ added in v0.10.0
ConnectionMetadataError contains only bounded, public-safe classification and text. Providers must sanitize these fields before returning observations.
func (*ConnectionMetadataError) UnmarshalJSON ¶ added in v0.10.0
func (value *ConnectionMetadataError) UnmarshalJSON(data []byte) error
UnmarshalJSON validates public-safe error shape and bounded text.
type ConnectionMetadataEvent ¶ added in v0.10.0
type ConnectionMetadataEvent struct {
Snapshot ConnectionMetadataSnapshot `json:"snapshot"`
Removed bool `json:"removed"`
}
ConnectionMetadataEvent carries a complete snapshot, or an ordered tombstone. Removed events retain connection identity and revision but contain no facts.
func (*ConnectionMetadataEvent) UnmarshalJSON ¶ added in v0.10.0
func (event *ConnectionMetadataEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON validates event shape and ordered removal tombstones.
type ConnectionMetadataObservation ¶ added in v0.10.0
type ConnectionMetadataObservation struct {
State string `json:"state"`
Value any `json:"value"`
ObservedAt time.Time `json:"observedAt"`
Error *ConnectionMetadataError `json:"error,omitempty"`
}
ConnectionMetadataObservation reports success or unavailable, not lifecycle state. A success requires a nonzero UTC observation time and a JSON value. Unavailable requires an error and has neither a value nor an observation time.
func (ConnectionMetadataObservation) MarshalJSON ¶ added in v0.10.0
func (observation ConnectionMetadataObservation) MarshalJSON() ([]byte, error)
MarshalJSON emits the observation union without unavailable payload fields.
func (*ConnectionMetadataObservation) UnmarshalJSON ¶ added in v0.10.0
func (observation *ConnectionMetadataObservation) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects invalid observation states and payload shapes.
type ConnectionMetadataProvider ¶ added in v0.10.0
type ConnectionMetadataProvider interface {
GetConnectionMetadata(context.Context, string) (ConnectionMetadataSnapshot, error)
RefreshConnectionMetadata(context.Context, string) (ConnectionMetadataSnapshot, error)
WatchConnectionMetadata(context.Context, ConnectionMetadataSink) error
}
ConnectionMetadataProvider exposes the SDK's authoritative, in-memory facts. GetConnectionMetadata never acquires facts. RefreshConnectionMetadata acquires only for an already active connection and never implicitly connects. Concurrent refresh callers share acquisition; cancellation detaches only that caller. WatchConnectionMetadata emits complete ordered snapshots and removal tombstones. Subscribe before fetching, and compare decimal revisions numerically within one provider registration. A generation is opaque and must never be sorted. Calls may overlap. Honor cancellation, return stable detached containers, and stop a watch when its sink returns an error. Public facts and errors must not contain credentials, private configuration, or raw native diagnostics. Remote callers must negotiate provider support rather than inspect static methods.
type ConnectionMetadataSink ¶ added in v0.10.0
type ConnectionMetadataSink func(ConnectionMetadataEvent) error
ConnectionMetadataSink receives one ordered event. An error terminates its watch.
type ConnectionMetadataSnapshot ¶ added in v0.10.0
type ConnectionMetadataSnapshot struct {
ConnectionID string `json:"connectionID"`
Generation string `json:"generation"`
Revision string `json:"revision"`
Active bool `json:"active"`
Refreshing bool `json:"refreshing"`
LastRefreshError *ConnectionMetadataError `json:"lastRefreshError,omitempty"`
Entries map[string]ConnectionMetadataEntry `json:"entries"`
}
ConnectionMetadataSnapshot is the authoritative state for one connection. An inactive inventory entry may have an empty generation. Revisions are positive canonical unsigned decimal strings and continue across generation changes.
func CloneConnectionMetadataSnapshot ¶ added in v0.10.0
func CloneConnectionMetadataSnapshot(snapshot ConnectionMetadataSnapshot) ConnectionMetadataSnapshot
CloneConnectionMetadataSnapshot detaches all mutable maps, slices, timestamps, and errors without JSON roundtripping or scalar coercion. Input must already pass ValidateConnectionMetadataSnapshot and remain stable during copying.
func (*ConnectionMetadataSnapshot) UnmarshalJSON ¶ added in v0.10.0
func (snapshot *ConnectionMetadataSnapshot) UnmarshalJSON(data []byte) error
UnmarshalJSON validates complete bounded state before assigning it.
type ConnectionMetadataUpdate ¶ added in v0.10.0
type ConnectionMetadataUpdate struct {
Set map[string]ConnectionMetadataObservation `json:"set"`
Remove []string `json:"remove"`
}
ConnectionMetadataUpdate is an atomic patch. Omitted keys remain unchanged. Remove cannot contain duplicates or overlap Set. JSON values accept native finite scalars, json.Number, string-keyed maps, and arrays/slices (not []byte). Structs, pointers, custom JSON encoders, and non-JavaScript-safe numbers are rejected. Providers must keep returned data stable until the SDK detaches it.
func (*ConnectionMetadataUpdate) UnmarshalJSON ¶ added in v0.10.0
func (update *ConnectionMetadataUpdate) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects malformed patches before exposing them to a coordinator.
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 resource operations and source sessions. 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 source 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]) 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]) GetConnectionMetadata ¶ added in v0.10.0
func (c *Controller[T]) GetConnectionMetadata(ctx context.Context, id string) (ConnectionMetadataSnapshot, error)
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]) InvalidateConnectionMetadata ¶ added in v0.10.0
func (c *Controller[T]) InvalidateConnectionMetadata(ctx context.Context, id string) error
InvalidateConnectionMetadata coalesces discovery invalidations through the same acquisition coordinator. An in-flight observation gets one follow-up pass.
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]) 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]) OpenSource ¶ added in v0.14.0
func (c *Controller[T]) OpenSource(ctx context.Context, request SourceOpenRequest, emitter SourceEmitter) (err error)
OpenSource dispatches a source session under a route lease and catalog fence.
func (*Controller[T]) RefreshConnectionMetadata ¶ added in v0.10.0
func (c *Controller[T]) RefreshConnectionMetadata(ctx context.Context, id string) (ConnectionMetadataSnapshot, error)
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]) 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]) 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]) WatchConnectionMetadata ¶ added in v0.10.0
func (c *Controller[T]) WatchConnectionMetadata(ctx context.Context, sink ConnectionMetadataSink) error
WatchConnectionMetadata subscribes before replaying current snapshots. A slow sink receives RESET_REQUIRED rather than silently losing an ordered tombstone.
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 ¶
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 ¶
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. Each Paths entry is an RFC6901 JSON pointer into the record body that starts with "/" and names a LIMITED subtree; empty Paths on partial or unknown coverage means the limitation is not localized.
func (Coverage) MarshalJSON ¶
MarshalJSON validates Coverage and emits canonical JSON without mutating caller-owned containers.
func (*Coverage) UnmarshalJSON ¶
UnmarshalJSON decodes Coverage, rejecting duplicate members, unknown fields, and invalid domain values.
type Dimension ¶
Dimension declares a required identity or query coordinate. AllowEmpty permits the literal empty string; it does not permit omitting the coordinate.
func (*Dimension) UnmarshalJSON ¶
UnmarshalJSON decodes Dimension, rejecting duplicate members, unknown fields, and invalid domain values.
type DocumentCoverage ¶ added in v0.14.4
type DocumentCoverage struct {
KnownAbsent []DocumentFieldPath `json:"knownAbsent"`
}
func (DocumentCoverage) MarshalJSON ¶ added in v0.14.4
func (c DocumentCoverage) MarshalJSON() ([]byte, error)
type DocumentFieldPath ¶ added in v0.14.4
type DocumentFieldPath struct {
Segments []FieldPathSegment `json:"segments"`
}
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 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 ¶
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" // FeatureSchemaResolver enables targeted schema resolution. FeatureSchemaResolver Feature = "schemaResolver" // 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" // FeatureConnectionMetadata enables public connection facts and refresh. FeatureConnectionMetadata Feature = "connectionMetadata" // FeatureSourceSessions enables phased source snapshot/update sessions. FeatureSourceSessions Feature = "sourceSessions" )
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 FieldPathSegment ¶ added in v0.14.4
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"}
}
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"}
}
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. 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" // OperationCreate admits only the create mutation verb. OperationCreate Operation = "create" // OperationMutationUpdate admits only the update mutation verb. 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" // OperationSourceUpdates advertises a source session that follows changes after its snapshot. OperationSourceUpdates Operation = "sourceUpdates" )
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 FromProtoQueryScope ¶ added in v0.13.0
func FromProtoQueryScope(p *resourcepb.QueryScope) (QueryScope, error)
FromProtoQueryScope decodes and validates a query scope.
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 ¶
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 // Source supplies a snapshot and subsequent updates. Source func(context.Context, *ClientT, SourceRequest, SourceEmitter) error 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; Source 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. Source request containers are copied independently from retained admission; its emitter 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 ¶
Representation identifies one body format. Revision tracks that format's contract independently of schema observations, records, and catalogs.
func (*Representation) UnmarshalJSON ¶
func (v *Representation) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes Representation, rejecting duplicate members, unknown fields, and invalid domain values.
type RepresentationBinding ¶ added in v0.14.4
type RepresentationBinding struct {
Representation Representation `json:"representation"`
}
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 ResourceActionIntent ¶ added in v0.15.0
type ResourceActionIntent struct {
PluginID string `json:"pluginID"`
Request ActionRequest `json:"request"`
}
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 ¶
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 ResourceNavigationIntent ¶ added in v0.15.0
type ResourceNavigationIntent struct {
}
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"`
// Description optionally explains the resource type to human or model consumers.
// It is descriptive metadata, not a capability or execution instruction.
Description string `json:"description,omitempty"`
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"`
AcquireOnConnect bool `json:"acquireOnConnect"`
}
ResourceType declares identity, query space, formats, and independent support. Query-only dimensions cannot be inferred from an object's identity scope.
func AdmitCatalogOperation ¶
func AdmitCatalogOperation(catalog Catalog, request any) (ResourceType, error)
AdmitCatalogOperation uses an already acquired catalog without another discovery RPC. A ReadTarget requests source 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 ¶
MarshalJSON emits the object-root action-schema subset without applying defaults.
func (Schema) Ptr ¶
Ptr returns a shallow pointer copy; nested maps and slices remain shared with s.
func (*Schema) UnmarshalJSON ¶
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"`
// 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 FromProtoSchemaBinding ¶ added in v0.20.0
func FromProtoSchemaBinding(p *resourcepb.SchemaBinding) (SchemaBinding, error)
FromProtoSchemaBinding rejects missing or invalid schema bindings. Successful output owns document bytes and optional observations independently.
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. This provider-only lookup is not a public document grant. Public consumers independently admit a target-qualified SchemaDocumentRequest.
type SchemaDocumentReference ¶
SchemaDocumentReference names one exact bounded document held for a demanded target.
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 SchemaDocumentRequest ¶ added in v0.20.0
type SchemaDocumentRequest struct {
Request SchemaRequest `json:"request"`
Reference SchemaDocumentReference `json:"reference"`
}
SchemaDocumentRequest qualifies an exact document reference with its demanded target. Consumers independently admit current access and the resolved binding; document identity or shared content alone is not an authorization grant.
func FromProtoSchemaDocumentRequest ¶ added in v0.20.0
func FromProtoSchemaDocumentRequest(p *resourcepb.SchemaDocumentRequest) (SchemaDocumentRequest, error)
FromProtoSchemaDocumentRequest admits an exact reference and its selected target. It rejects nil or invalid messages and independently owns mutable storage.
func (SchemaDocumentRequest) MarshalJSON ¶ added in v0.20.0
func (v SchemaDocumentRequest) MarshalJSON() ([]byte, error)
MarshalJSON validates the complete target-qualified document request.
func (*SchemaDocumentRequest) UnmarshalJSON ¶ added in v0.20.0
func (v *SchemaDocumentRequest) UnmarshalJSON(data []byte) error
UnmarshalJSON requires both the admitted target and exact document reference.
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 SchemaRequest ¶ added in v0.20.0
type SchemaRequest struct {
Route AccessRoute `json:"route"`
Type string `json:"type"`
Target SchemaTarget `json:"target"`
}
SchemaRequest asks for one schema under an explicitly admitted route and type. The auxiliary reference must have exactly the requested type. A representation target requires an explicit format ID and revision, never an inferred default. Successful resolution does not grant access to the referenced document.
func FromProtoSchemaRequest ¶ added in v0.20.0
func FromProtoSchemaRequest(p *resourcepb.SchemaRequest) (SchemaRequest, error)
FromProtoSchemaRequest rejects missing, unknown, or invalid target fields. Successful output owns all mutable storage independently.
func (SchemaRequest) MarshalJSON ¶ added in v0.20.0
func (v SchemaRequest) MarshalJSON() ([]byte, error)
MarshalJSON validates the route, type, and selected target before encoding.
func (*SchemaRequest) UnmarshalJSON ¶ added in v0.20.0
func (v *SchemaRequest) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects unknown, duplicate, null, and missing request fields.
type SchemaResolver ¶ added in v0.20.0
type SchemaResolver interface {
ResolveSchema(context.Context, SchemaRequest) (SchemaBinding, error)
}
SchemaResolver resolves one explicitly selected representation or auxiliary resource schema. It never enumerates schema bindings or selects a default representation. Absence of this optional interface means unsupported enrichment. Calls may run concurrently; honor cancellation and return stable, independently owned bindings. Schema resolution does not grant resource or document access.
type SchemaTarget ¶ added in v0.20.0
type SchemaTarget struct {
Representation *Representation `json:"representation,omitempty"`
Auxiliary *AuxiliarySchemaTarget `json:"auxiliary,omitempty"`
}
SchemaTarget selects exactly one current representation or auxiliary resource schema. Callers resolve default representations before constructing a target. Nested references and pointers are borrowed for the duration of resolution.
func (SchemaTarget) MarshalJSON ¶ added in v0.20.0
func (v SchemaTarget) MarshalJSON() ([]byte, error)
MarshalJSON requires exactly one explicit, valid target.
func (*SchemaTarget) UnmarshalJSON ¶ added in v0.20.0
func (v *SchemaTarget) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects unknown, duplicate, null, and ambiguous target fields.
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 ¶
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.
type SourceAcquisition ¶ added in v0.14.0
type SourceAcquisition struct {
Kind string `json:"kind"`
Language string `json:"language,omitempty"`
Query *Value `json:"query,omitempty"`
}
func FromProtoSourceAcquisition ¶ added in v0.14.0
func FromProtoSourceAcquisition(p *resourcepb.SourceAcquisition) (SourceAcquisition, error)
type SourceBegin ¶ added in v0.14.0
type SourceBegin struct {
Mode string `json:"mode"`
}
func FromProtoSourceBegin ¶ added in v0.14.0
func FromProtoSourceBegin(p *resourcepb.SourceBegin) (SourceBegin, error)
type SourceChange ¶ added in v0.14.0
type SourceChange struct {
Kind string `json:"kind"`
Observation *SourceObservation `json:"observation,omitempty"`
Reference *ResourceReference `json:"reference,omitempty"`
SourceRevision *string `json:"sourceRevision,omitempty"`
}
func FromProtoSourceChange ¶ added in v0.14.0
func FromProtoSourceChange(p *resourcepb.SourceChange) (SourceChange, error)
type SourceChanges ¶ added in v0.14.0
type SourceChanges struct {
Changes []SourceChange `json:"changes"`
Coverage *SourceCoverage `json:"coverage,omitempty"`
}
func FromProtoSourceChanges ¶ added in v0.14.0
func FromProtoSourceChanges(p *resourcepb.SourceChanges) (SourceChanges, error)
type SourceCoverage ¶ added in v0.14.0
type SourceCoverage struct {
Enumeration string `json:"enumeration"`
Consistency string `json:"consistency"`
Limitations []string `json:"limitations"`
}
func FromProtoSourceCoverage ¶ added in v0.14.0
func FromProtoSourceCoverage(p *resourcepb.SourceCoverage) (SourceCoverage, error)
type SourceEmitter ¶ added in v0.14.0
type SourceEmitter interface {
Snapshot(ctx context.Context, observations []SourceObservation) error
EndSnapshot(ctx context.Context, coverage SourceCoverage, continuity string) error
Changes(ctx context.Context, changes []SourceChange, coverage *SourceCoverage) error
Reset(ctx context.Context, reason, message string) error
}
SourceEmitter emits source data while the framework enforces session phases and limits.
type SourceFailure ¶ added in v0.14.0
func FromProtoSourceFailure ¶ added in v0.14.0
func FromProtoSourceFailure(p *resourcepb.SourceFailure) (SourceFailure, error)
type SourceFrame ¶ added in v0.14.0
type SourceFrame struct {
SessionID string `json:"sessionId"`
Generation string `json:"generation"`
Sequence uint64 `json:"-"`
Begin *SourceBegin `json:"begin,omitempty"`
Snapshot *SourceSnapshot `json:"snapshot,omitempty"`
SnapshotEnd *SourceSnapshotEnd `json:"snapshotEnd,omitempty"`
Changes *SourceChanges `json:"changes,omitempty"`
Reset *SourceReset `json:"reset,omitempty"`
Failed *SourceFailure `json:"failed,omitempty"`
}
func FromProtoSourceFrame ¶ added in v0.14.0
func FromProtoSourceFrame(p *resourcepb.SourceFrame) (SourceFrame, error)
func (SourceFrame) MarshalJSON ¶ added in v0.14.4
func (f SourceFrame) MarshalJSON() ([]byte, error)
MarshalJSON emits source sequence as decimal text, never a JavaScript number.
func (*SourceFrame) UnmarshalJSON ¶ added in v0.14.4
func (f *SourceFrame) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects noncanonical or out-of-range source sequence text.
type SourceLimits ¶ added in v0.14.0
type SourceLimits struct {
MaxFrameBytes uint32 `json:"maxFrameBytes"`
MaxBatchItems uint32 `json:"maxBatchItems"`
}
func FromProtoSourceLimits ¶ added in v0.14.0
func FromProtoSourceLimits(p *resourcepb.SourceLimits) (SourceLimits, error)
type SourceObservation ¶ added in v0.14.0
type SourceObservation struct {
Record SourceRecord `json:"record"`
Metadata *ResourceMetadata `json:"metadata,omitempty"`
DisplayName *string `json:"displayName,omitempty"`
DocumentCoverage DocumentCoverage `json:"documentCoverage"`
}
func FromProtoSourceObservation ¶ added in v0.14.0
func FromProtoSourceObservation(p *resourcepb.SourceObservation) (SourceObservation, error)
type SourceOpenRequest ¶ added in v0.14.0
type SourceOpenRequest struct {
SessionID string `json:"sessionId"`
Generation string `json:"generation"`
Target ReadTarget `json:"target"`
Mode string `json:"mode"`
Acquisition SourceAcquisition `json:"acquisition"`
Limits SourceLimits `json:"limits"`
Binding RepresentationBinding `json:"binding"`
}
func FromProtoSourceOpenRequest ¶ added in v0.14.0
func FromProtoSourceOpenRequest(p *resourcepb.SourceOpenRequest) (SourceOpenRequest, error)
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 SourcePhaseTracker ¶ added in v0.14.0
type SourcePhaseTracker struct {
// contains filtered or unexported fields
}
SourcePhaseTracker validates frames from one source session. Its methods are safe for concurrent use.
func NewCatalogBoundSourcePhaseTracker ¶ added in v0.14.2
func NewCatalogBoundSourcePhaseTracker(request SourceOpenRequest, descriptor ResourceType) *SourcePhaseTracker
NewCatalogBoundSourcePhaseTracker also validates records and removals against the descriptor admitted for this session. The descriptor must remain immutable.
func NewSourcePhaseTracker ¶ added in v0.14.0
func NewSourcePhaseTracker(request SourceOpenRequest, declaredContinuity string) *SourcePhaseTracker
func (*SourcePhaseTracker) Admit ¶ added in v0.14.0
func (t *SourcePhaseTracker) Admit(f SourceFrame) error
Admit validates one frame and advances the session only when it is valid.
func (*SourcePhaseTracker) AdmitSized ¶ added in v0.14.0
func (t *SourcePhaseTracker) AdmitSized(f SourceFrame, size int) error
AdmitSized validates a frame using its already encoded protobuf size. The caller must supply the size of the exact frame being admitted.
func (*SourcePhaseTracker) Close ¶ added in v0.14.0
func (t *SourcePhaseTracker) Close()
Close marks the tracker cancelled. It is idempotent and does not wait for the peer.
func (*SourcePhaseTracker) TransportError ¶ added in v0.14.0
func (t *SourcePhaseTracker) TransportError(err error) error
TransportError reports EOF or another transport loss. A terminal stream ends with io.EOF.
type SourceProvider ¶ added in v0.14.0
type SourceProvider interface {
OpenSource(ctx context.Context, request SourceOpenRequest, emitter SourceEmitter) error
}
SourceProvider opens a source session and emits its snapshot and updates.
type SourceRecord ¶ added in v0.14.4
type SourceRecord struct {
Reference ResourceReference `json:"reference"`
Body Value `json:"body"`
Representation Representation `json:"representation"`
Coverage Coverage `json:"coverage"`
SourceRevision *string `json:"sourceRevision,omitempty"`
}
func CompactSourceRecord ¶ added in v0.14.4
func CompactSourceRecord(record Record) SourceRecord
CompactSourceRecord adapts a finite record to the source observation envelope.
type SourceRequest ¶ added in v0.14.0
type SourceRequest struct {
Target ReadTarget
Representation Representation
Limits SourceLimits
}
SourceRequest is passed to Registration.Source. Limits are the session limits; one Changes call must stay within Limits.MaxBatchItems.
type SourceReset ¶ added in v0.14.0
func FromProtoSourceReset ¶ added in v0.14.0
func FromProtoSourceReset(p *resourcepb.SourceReset) (SourceReset, error)
type SourceSnapshot ¶ added in v0.14.0
type SourceSnapshot struct {
Observations []SourceObservation `json:"observations"`
}
func FromProtoSourceSnapshot ¶ added in v0.14.0
func FromProtoSourceSnapshot(p *resourcepb.SourceSnapshot) (SourceSnapshot, error)
type SourceSnapshotEnd ¶ added in v0.14.0
type SourceSnapshotEnd struct {
Coverage SourceCoverage `json:"coverage"`
Continuity string `json:"continuity"`
}
func FromProtoSourceSnapshotEnd ¶ added in v0.14.0
func FromProtoSourceSnapshotEnd(p *resourcepb.SourceSnapshotEnd) (SourceSnapshotEnd, error)
type SourceStream ¶ added in v0.14.0
type SourceStream interface {
Recv() (SourceFrame, error)
Close()
}
SourceStream is a caller-owned source session. Callers must Close the stream or cancel the opening context when they stop receiving, including on errors. Close is idempotent and unblocks a concurrent Recv.
type SourceStreamOpener ¶ added in v0.14.0
type SourceStreamOpener interface {
OpenSourceStream(ctx context.Context, request SourceOpenRequest) (SourceStream, error)
}
SourceStreamOpener opens validated host-side source streams.
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 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 ¶
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 ¶
TimestampValue constructs an exact timestamp without floating-point seconds.
func ValueFromNative ¶
ValueFromNative preserves native scalar types without a JSON float roundtrip. Unsupported native types fail rather than stringify or silently lose intent.
func (Value) MarshalJSON ¶
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 ¶
UnmarshalJSON admits the strict tagged encoding without changing the receiver on failure. Duplicate members, malformed Unicode, and missing or inactive payloads are rejected.
Source Files
¶
- acquisition_timeout.go
- action_descriptor_json.go
- action_schema.go
- activity.go
- activity_validation.go
- adapter_admission.go
- adapters.go
- adapters_ancillary.go
- adapters_relationship.go
- adapters_source.go
- admission_obs.go
- ancillary.go
- ancillary_types.go
- catalog_revision.go
- connection_copy.go
- connection_metadata.go
- connection_overlay.go
- controller.go
- controller_admission.go
- controller_dispatch.go
- controller_inventory.go
- controller_lifecycle.go
- controller_lifecycle_obs.go
- controller_metadata.go
- controller_source.go
- doc.go
- domain.go
- domain_json.go
- errors.go
- features.go
- native_query.go
- presentation_validation.go
- provider_options.go
- read_target_identity.go
- relationship_request.go
- relationship_request_json.go
- relationship_validation.go
- route_catalog_revision.go
- schema_copy.go
- schema_property_json.go
- schema_request.go
- schema_request_json.go
- schema_validation.go
- source.go
- source_contract.go
- source_document.go
- source_frame_json.go
- source_phase.go
- utility_context.go
- validation.go
- value_json.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
wirecost
Package wirecost counts protobuf message and field occurrences.
|
Package wirecost counts protobuf message and field occurrences. |
|
Package plugin transports resource v2 providers over bounded, validated gRPC messages.
|
Package plugin transports resource v2 providers over bounded, validated gRPC messages. |