connector

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 16 Imported by: 7 modules, 118 packages

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

README

Domainry Connector SDK for Go

This repository owns the stable public contracts used by Domainry Plane, official Domainry Connectors, reviewed third-party Connectors, and customer-private Connectors.

The SDK defines Provider descriptors, operations, reliability semantics, host-supplied transports, Provider factories, webhook verification, connection testing, reconciliation, error classification, and contract-test helpers. It does not implement Integration persistence, authorization, audit, secret storage, scheduling, Admin surfaces, Builder behavior, or concrete Providers. Connector definitions and implementations live in domainry-connectors; domainry-integration owns their configured runtime state and execution.

OAuth connection-test requirements

Providers may implement OAuthConnectionTestScopeProvider for their fixed connection probe. Each outer element is an alternative; every scope within an alternative is required. A declared empty alternative means the probe needs no OAuth scopes. An absent declaration retains legacy behavior. The registry copies both slice levels at registration and on reads. Integration evaluates these requirements against the actual grant; this metadata never requests extra scopes or decides access to business tools. The optional authorizer interface is unchanged.

OAuth operation requirements

OAuthOperationScopeProvider separately declares the OAuth grants for each registered operation. The registry snapshots these declarations by operation key and copies both slice levels when returning them. Missing declarations never grant account-read access. Hosts must independently verify current-user account ownership, actual grants, the registered operation hash and its read effect; neither requested scopes nor probe requirements authorize a business operation.

Dependency boundary

The SDK must not import either of these modules:

  • github.com/domainry/domainry-plane
  • github.com/domainry/domainry-connectors

Both modules depend on this SDK instead.

Package layout

  • The root package owns provider, gateway, adapter, transport, reliability, and background-processing contracts.
  • contracttest contains reusable implementation conformance tests.
  • examples contains public integration examples.

The SDK intentionally has no persistence or modulehost package: the host supplies governed transport capabilities, Integration owns connection and execution infrastructure, and concrete Connectors own Provider implementations.

Development

make fmt-check
make test
make vet
make boundary
make license-check
make vulnerability-check

make release-check runs every required release gate. Public compatibility is identified by SDKVersion, ContractVersion, and ContractSHA256; consumers should depend on an immutable tagged version.

License

The SDK is available under the MIT License. See LICENSE.

Calendar read contracts

The optional calendar package defines a separate calendar-read-v1 contract for provider-neutral calendar lists, windowed events, event details and availability. It includes deterministic operation identities and time validation; it owns no account, authorization or transport. Date-only all-day bounds remain dates with exclusive ends. Instants require offsets, and ambiguous local times cannot be silently selected. Partial availability never implies free time.

Mail read contracts

The optional mail package defines mail-read-v1 with independent identities for metadata listing, native-syntax search and bounded plain-text message reads. Queries declare gmail or graph-kql; providers reject a mismatched dialect. Pages default to 10 messages (maximum 25), bodies to 16 KiB (maximum 64 KiB). IDs are scoped to the authorized account. Missing fields remain unknown; pagination, provider caps, omitted body content and truncation are explicit. Attachments and external linked content are outside this read contract. The package contains no authorization, network, mailbox storage or send API.

The independent web package defines public-web-read-v1 for bounded public-web search and page reads. Ranked search results never imply an exhaustive match set; page source completeness remains unknown/partial and local truncation is explicit. URL normalization checks syntax, common non-public literal addresses, standard ports and credentials, with no DNS or outbound I/O; hosts and remote fetch services must enforce network policies separately. Each operation has a fixed contract hash. The generic Connector contract and calendar/mail identities remain unchanged.

Calendar and mail write contracts

calendarwrite defines the separate calendar-write-v1 contract for inspecting an exact event, creating an event, and applying a version-checked patch. A single event and a whole recurring series require distinct explicit scopes. The target attendee list and requested notification policy are part of the preview; a series can also notify separately changed occurrences. Instants must have offsets matching their IANA zones, and all-day ends remain exclusive. Omitted patch fields stay unchanged; explicit empty description/location or attendee arrays clear those fields. Providers retain their native concurrency checks and never treat a wildcard as an expected version.

mailwrite defines mail-write-v1 for new mail and replies with explicit To, CC, BCC, subject and plain text. Replies validate current original metadata and Reply-To recipients before provider-specific threading. Sender, headers and correlation identifiers come from the trusted invocation envelope. Receipts record provider acceptance and explicitly unknown delivery; a Graph 202 needs no invented message ID.

Both packages reject undeclared request fields and bound JSON requests to 1 MiB, allowing worst-case escaping of bounded 64 KiB text. They do not grant account access, confirm operations, persist receipts or retry external writes. Integration and the consuming execution host own those concerns. The calendar and mail read contracts, existing Provider registrations and generic SDK contract remain unchanged. Provider and product integration of these optional contracts is a separate delivery step.

Documentation

Overview

Package connector defines the public, versioned boundary for project-owned Connector providers. It owns its DTOs and does not expose Runtime internal application, persistence, secret-store, worker, or transport types.

Index

Constants

View Source
const ContractSHA256 = "664cb625e96fed3fcfd88c6b25e0087c63aa18e22dd2c960ab9d858b85941fee"
View Source
const ContractVersion = "connector-contract-v16"
View Source
const ErrorContractInvalidCode = "connector.error_contract_invalid"
View Source
const SDKVersion = "v0.1.0-dev.19"

SDKVersion identifies the release line of this module independently from the compatibility identity of its public Connector contract.

Variables

View Source
var (
	ErrRegistryFrozen    = errors.New("connector provider registry is frozen")
	ErrProviderRequired  = errors.New("connector provider adapter is required")
	ErrProviderDuplicate = errors.New("connector provider is already registered")
)

Functions

func ApplyConfigDefaults

func ApplyConfigDefaults(fields []ConfigField, config map[string]any) (map[string]any, error)

ApplyConfigDefaults materializes schema-owned, non-secret defaults without replacing any value already supplied by a manifest, tenant, or administrator. Decoding on every call also gives mutable JSON defaults an independent value.

func Call

func Call[I any, O any](ctx context.Context, gateway Gateway, operation CallOperation[I, O], input I) (O, error)

func ComputedContractSHA256

func ComputedContractSHA256() string

func NewProviderError

func NewProviderError(classification ErrorClassification, code string, cause error) error

NewProviderError creates a classified provider failure. Invalid class/code input is converted to a permanent contract error rather than guessed or allowed to become retryable.

func PermanentError

func PermanentError(code string, cause error) error

func ProviderErrorCodeOf

func ProviderErrorCodeOf(err error) (string, bool)

func ProviderIdentity

func ProviderIdentity(connectorKey, providerKey string) string

func ResolveOAuthConnectionTestScopes added in v0.1.1

func ResolveOAuthConnectionTestScopes(adapter Adapter) ([][]string, bool)

func ResolveOAuthOperationScopes added in v0.1.1

func ResolveOAuthOperationScopes(adapter Adapter, operationKey string) ([][]string, bool)

func RetryableError

func RetryableError(code string, cause error) error

func UncertainError

func UncertainError(code string, cause error) error

Types

type Adapter

type Adapter interface {
	Descriptor() ProviderDescriptor
	Call(context.Context, CallRequest) (CallResult, error)
}

Adapter is the single Integration-facing project Connector boundary. One Adapter may own many differently typed operations for one exact provider.

func NewProvider

func NewProvider(schema ProviderSchema, operations ...BoundOperation) (Adapter, error)

type BackgroundCapabilityProvider

type BackgroundCapabilityProvider interface {
	BackgroundProcessor() (BackgroundProcessor, bool)
}

BackgroundCapabilityProvider is implemented by Registry snapshots. The boolean is false when the concrete Provider has no background capability.

type BackgroundCleanupCapabilityProvider

type BackgroundCleanupCapabilityProvider interface {
	BackgroundCleanupProcessor() (BackgroundCleanupProcessor, bool)
}

type BackgroundCleanupProcessor

type BackgroundCleanupProcessor interface {
	CleanupBackground(context.Context, Connection, map[string]string, time.Time, Principal) (map[string]string, error)
}

BackgroundCleanupProcessor lets a provider tear down remote resources before Integration deletes a connection. Integration still resolves and persists secrets.

type BackgroundCommit

type BackgroundCommit struct {
	OperationKey   string          `json:"operation_key"`
	ContractSHA256 string          `json:"contract_sha256"`
	Payload        json.RawMessage `json:"payload"`
}

BackgroundCommit is a provider operation that Integration executes only after the state transition and events are durably committed. It is used for acknowledgements and other post-commit provider effects.

func (BackgroundCommit) Validate

func (c BackgroundCommit) Validate() error

type BackgroundEvent

type BackgroundEvent struct {
	ExternalID string          `json:"external_id"`
	EventType  string          `json:"event_type"`
	Payload    json.RawMessage `json:"payload"`
}

BackgroundEvent is provider-normalized input that Integration must durably accept before executing any returned Commit operation.

func (BackgroundEvent) Validate

func (e BackgroundEvent) Validate() error

type BackgroundProcessor

type BackgroundProcessor interface {
	BackgroundTasks(Connection) []BackgroundTaskDescriptor
	ProcessBackground(context.Context, BackgroundRequest) (BackgroundResult, error)
}

BackgroundProcessor is optional provider behavior. Implementations perform provider I/O only through the Transport supplied to their constructor.

type BackgroundRequest

type BackgroundRequest struct {
	TaskKey       string                     `json:"task_key"`
	StateVersion  int                        `json:"state_version"`
	Connection    Connection                 `json:"connection"`
	State         json.RawMessage            `json:"state,omitempty"`
	RelatedStates map[string]json.RawMessage `json:"related_states,omitempty"`
	Secrets       map[string]string          `json:"secrets,omitempty"`
	Now           time.Time                  `json:"now"`
	Principal     Principal                  `json:"principal"`
}

BackgroundRequest is a single fenced transition request. State is opaque to Integration and must contain exactly one JSON value when non-empty.

func (BackgroundRequest) Validate

func (r BackgroundRequest) Validate() error

type BackgroundResult

type BackgroundResult struct {
	State         json.RawMessage    `json:"state"`
	NextDueAt     time.Time          `json:"next_due_at,omitempty"`
	Events        []BackgroundEvent  `json:"events,omitempty"`
	Commit        []BackgroundCommit `json:"commit,omitempty"`
	WakeTasks     []string           `json:"wake_tasks,omitempty"`
	SecretUpdates map[string]string  `json:"secret_updates,omitempty"`
}

func (BackgroundResult) Validate

func (r BackgroundResult) Validate() error

type BackgroundTaskDescriptor

type BackgroundTaskDescriptor struct {
	Key          string `json:"key"`
	StateVersion int    `json:"state_version"`
}

BackgroundTaskDescriptor declares one provider-owned durable task. Integration owns scheduling, leases, persistence, secrets, transports, and audit; the provider owns the state payload and transition semantics.

func (BackgroundTaskDescriptor) Validate

func (d BackgroundTaskDescriptor) Validate() error

type BoundOperation

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

func BindCall

func BindCall[I any, O any](operation CallOperation[I, O], handler CallHandler[I, O]) (BoundOperation, error)

BindCall performs the only type erasure for a synchronous operation.

func BindEnqueueDelivery

func BindEnqueueDelivery[I any](operation EnqueueOperation[I], handler DeliveryHandler[I]) (BoundOperation, error)

BindEnqueueDelivery erases the worker-side delivery handler for an enqueue operation. It does not provide a second Action-side execution channel.

func BindStartOperationDelivery

func BindStartOperationDelivery[I any](operation StartOperation[I], handler DeliveryHandler[I]) (BoundOperation, error)

BindStartOperationDelivery erases the worker-side delivery handler that starts a long-running external operation after the local UoW commits.

func (BoundOperation) Descriptor

func (b BoundOperation) Descriptor() OperationDescriptor

type CallHandler

type CallHandler[I any, O any] func(context.Context, TypedRequest[I]) (TypedResult[O], error)

type CallOperation

type CallOperation[I any, O any] struct {
	ConnectorKey   string
	ProviderKey    string
	Key            string
	ContractSHA256 string
	Reliability    ReliabilityContract
}

CallOperation is a synchronous operation whose typed output is required by the caller before it can continue.

func (CallOperation[I, O]) Descriptor

func (o CallOperation[I, O]) Descriptor() OperationDescriptor

type CallRequest

type CallRequest struct {
	ConnectorKey   string            `json:"connector_key"`
	ProviderKey    string            `json:"provider_key"`
	OperationKey   string            `json:"operation_key"`
	ContractSHA256 string            `json:"contract_sha256"`
	Mode           OperationMode     `json:"mode"`
	Connection     Connection        `json:"connection"`
	Payload        json.RawMessage   `json:"payload"`
	RequestRef     string            `json:"request_ref,omitempty"`
	Headers        map[string]string `json:"headers,omitempty"`
	Secrets        map[string]string `json:"secrets,omitempty"`
	Delivery       bool              `json:"delivery,omitempty"`
	Timeout        time.Duration     `json:"timeout,omitempty"`
	Principal      Principal         `json:"principal"`
}

CallRequest is the type-erased Integration-to-provider envelope. Payload is decoded by a BoundOperation before project provider code is invoked. Secrets contains Integration-resolved material only for fields declared by the selected Provider descriptor; Adapters must not resolve references.

type CallResult

type CallResult struct {
	Payload        json.RawMessage       `json:"payload,omitempty"`
	ResponseRef    string                `json:"response_ref,omitempty"`
	SecretUpdates  map[string]string     `json:"secret_updates,omitempty"`
	ResourceHealth *ResourceHealthReport `json:"resource_health,omitempty"`
}

type CompensationContract

type CompensationContract struct {
	Mode         CompensationMode `json:"mode"`
	OperationKey string           `json:"operation_key,omitempty"`
}

type CompensationMode

type CompensationMode string
const (
	CompensationNone     CompensationMode = "none"
	CompensationExplicit CompensationMode = "explicit"
	CompensationSaga     CompensationMode = "saga"
)

type ConfigField

type ConfigField struct {
	Key          string                       `json:"key"`
	Name         string                       `json:"name"`
	Description  string                       `json:"description,omitempty"`
	Type         ConfigFieldType              `json:"type"`
	I18n         map[string]FieldLocalization `json:"i18n,omitempty"`
	Required     bool                         `json:"required"`
	Default      json.RawMessage              `json:"default,omitempty"`
	Validation   ConfigValidation             `json:"validation,omitempty"`
	RequiredWith []string                     `json:"required_with,omitempty"`
}

type ConfigFieldType

type ConfigFieldType string
const (
	ConfigFieldText    ConfigFieldType = "text"
	ConfigFieldEmail   ConfigFieldType = "email"
	ConfigFieldInteger ConfigFieldType = "integer"
	ConfigFieldDecimal ConfigFieldType = "decimal"
	ConfigFieldBoolean ConfigFieldType = "boolean"
	ConfigFieldSelect  ConfigFieldType = "select"
	ConfigFieldJSON    ConfigFieldType = "json"
)

type ConfigValidation

type ConfigValidation struct {
	MinLength int      `json:"min_length,omitempty"`
	MaxLength int      `json:"max_length,omitempty"`
	Min       *float64 `json:"min,omitempty"`
	Max       *float64 `json:"max,omitempty"`
	Pattern   string   `json:"pattern,omitempty"`
	Options   []string `json:"options,omitempty"`
}

type ConfigValidator

type ConfigValidator interface {
	ValidateConfig(Connection) error
}

ConfigValidator is optional. Integration supplies the normalized connection and retains ownership of persistence and secret resolution; providers may only validate provider-specific configuration semantics.

type Connection

type Connection struct {
	Key          string            `json:"key"`
	WorkspaceID  string            `json:"workspace_id,omitempty"`
	ConnectorKey string            `json:"connector_key"`
	ProviderKey  string            `json:"provider_key"`
	Name         string            `json:"name,omitempty"`
	Status       string            `json:"status,omitempty"`
	Config       map[string]any    `json:"config,omitempty"`
	SecretRefs   map[string]string `json:"secret_refs,omitempty"`
	CreatedBy    string            `json:"created_by,omitempty"`
	CreatedAt    string            `json:"created_at,omitempty"`
	UpdatedAt    string            `json:"updated_at,omitempty"`
}

Connection contains only SecretRefs declared by the selected Provider descriptor. Integration retains reference resolution and persistence ownership.

type ConnectionTester

type ConnectionTester interface {
	TestConnection(context.Context, TestConnectionRequest) (TestConnectionResult, error)
}

ConnectionTester is optional. Integration discovers it by type assertion and fails closed when a provider does not publish connection testing support.

type DeliveryHandler

type DeliveryHandler[I any] func(context.Context, TypedRequest[I]) (DeliveryResult, error)

type DeliveryResult

type DeliveryResult struct {
	ResponseRef    string
	SecretUpdates  map[string]string
	ResourceHealth *ResourceHealthReport
}

type EnqueueOperation

type EnqueueOperation[I any] struct {
	ConnectorKey   string
	ProviderKey    string
	Key            string
	ContractSHA256 string
	Reliability    ReliabilityContract
}

EnqueueOperation is an asynchronous command. Its provider result is delivery metadata only; no typed output is returned to the Action Handler.

func (EnqueueOperation[I]) Descriptor

func (o EnqueueOperation[I]) Descriptor() OperationDescriptor

type ErrorClassification

type ErrorClassification string

ErrorClassification is the closed recovery decision reported by provider code. Runtime still applies the operation's idempotency and retry policy; a retryable classification alone never authorizes a retry.

const (
	ErrorRetryable ErrorClassification = "retryable"
	ErrorPermanent ErrorClassification = "permanent"
	ErrorUncertain ErrorClassification = "uncertain"
)

func ErrorClassificationOf

func ErrorClassificationOf(err error) (ErrorClassification, bool)

type FieldLocalization

type FieldLocalization struct {
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
}

type FilesystemOperation

type FilesystemOperation string
const (
	FilesystemOperationProbe  FilesystemOperation = "probe"
	FilesystemOperationRead   FilesystemOperation = "read"
	FilesystemOperationWrite  FilesystemOperation = "write"
	FilesystemOperationDelete FilesystemOperation = "delete"
)

type FilesystemRequest

type FilesystemRequest struct {
	Root         string              `json:"root"`
	Path         string              `json:"path,omitempty"`
	Operation    FilesystemOperation `json:"operation"`
	Content      []byte              `json:"content,omitempty"`
	MaxReadBytes int64               `json:"max_read_bytes,omitempty"`
}

type FilesystemResult

type FilesystemResult struct {
	Path    string `json:"path,omitempty"`
	Content []byte `json:"content,omitempty"`
	Size    int64  `json:"size,omitempty"`
	Exists  bool   `json:"exists"`
}

type FilesystemTransport

type FilesystemTransport interface {
	ExecuteFilesystem(context.Context, FilesystemRequest) (FilesystemResult, error)
}

FilesystemTransport is an optional host-owned capability for Providers that operate on a configured local filesystem. The host owns root and path validation, permissions, bounded reads, durable staged writes, and deletion.

type Gateway

type Gateway interface {
	Call(context.Context, CallRequest) (CallResult, error)
}

Gateway is implemented by the Integration execution boundary. Generated clients may call it only through the typed helpers in this package.

type HTTPRequest

type HTTPRequest struct {
	Method  string              `json:"method"`
	URL     string              `json:"url"`
	Headers map[string][]string `json:"headers,omitempty"`
	// SecretHeaders contains resolved secret-bearing header values that Integration
	// injects immediately before dispatch. Keys must not occur in Headers.
	SecretHeaders map[string][]string `json:"-"`
	// SecretQuery is resolved secret material that Integration injects immediately
	// before dispatch. It is deliberately excluded from serialization.
	SecretQuery map[string]string `json:"-"`
	// SecretForm contains resolved form fields that Integration injects into an
	// application/x-www-form-urlencoded body immediately before dispatch.
	// Keys must not occur in the public Body.
	SecretForm map[string]string `json:"-"`
	// SecretJSON contains resolved string fields that Integration injects into a
	// top-level application/json object immediately before dispatch. Keys must
	// not occur in the public Body.
	SecretJSON       map[string]string `json:"-"`
	Body             []byte            `json:"body,omitempty"`
	MaxResponseBytes int64             `json:"max_response_bytes,omitempty"`
}

type HTTPResponse

type HTTPResponse struct {
	StatusCode int                 `json:"status_code"`
	Headers    map[string][]string `json:"headers,omitempty"`
	Body       []byte              `json:"body,omitempty"`
}

type IdempotencyContract

type IdempotencyContract struct {
	Strategy            IdempotencyStrategy `json:"strategy"`
	KeyRetentionSeconds int                 `json:"key_retention_seconds,omitempty"`
}

type IdempotencyStrategy

type IdempotencyStrategy string
const (
	IdempotencyNone        IdempotencyStrategy = "none"
	IdempotencyNatural     IdempotencyStrategy = "natural"
	IdempotencyProviderKey IdempotencyStrategy = "provider_key"
)

type Identity

type Identity struct {
	SDKVersion      string `json:"sdk_version"`
	ContractVersion string `json:"contract_version"`
	ContractSHA256  string `json:"contract_sha256"`
}

Identity is recorded by hosts and generated projects so semantic SDK releases cannot accidentally hide a public contract change.

func CurrentIdentity

func CurrentIdentity() Identity

CurrentIdentity returns the immutable identity of this SDK build.

type MQTTRequest

type MQTTRequest struct {
	BrokerURL         string        `json:"broker_url"`
	ClientID          string        `json:"client_id,omitempty"`
	Topic             string        `json:"topic,omitempty"`
	Payload           []byte        `json:"payload,omitempty"`
	QoS               byte          `json:"qos,omitempty"`
	ProbeOnly         bool          `json:"probe_only,omitempty"`
	Timeout           time.Duration `json:"timeout,omitempty"`
	TLSServerName     string        `json:"tls_server_name,omitempty"`
	TLSCAPEM          string        `json:"tls_ca_pem,omitempty"`
	SecretUsername    string        `json:"-"`
	SecretPassword    string        `json:"-"`
	SecretCertificate string        `json:"-"`
	SecretPrivateKey  string        `json:"-"`
}

type MQTTResult

type MQTTResult struct {
	Connected bool   `json:"connected"`
	Accepted  bool   `json:"accepted,omitempty"`
	PacketID  uint16 `json:"packet_id,omitempty"`
}

type MQTTTransport

type MQTTTransport interface {
	ExecuteMQTT(context.Context, MQTTRequest) (MQTTResult, error)
}

MQTTTransport is an optional host-owned capability for Providers that connect to MQTT brokers. The host owns sockets, TLS, packet framing, deadlines, QoS acknowledgement, and secret injection.

type OAuthAuthorizationCapabilityProvider added in v0.1.1

type OAuthAuthorizationCapabilityProvider interface {
	OAuthAuthorizer() (OAuthAuthorizer, bool)
}

OAuthAuthorizationCapabilityProvider preserves the optional protocol capability when a host freezes a registry, without advertising it for non-OAuth providers.

type OAuthAuthorizationRequest added in v0.1.1

type OAuthAuthorizationRequest struct {
	Connection  Connection `json:"connection"`
	ClientID    string     `json:"client_id"`
	RedirectURI string     `json:"redirect_uri"`
	Scopes      []string   `json:"scopes"`
	// State and CodeChallenge come from fresh cryptographic randomness generated
	// and durably bound to the authenticated session by Integration.
	State         string `json:"-"`
	CodeChallenge string `json:"code_challenge"`
}

type OAuthAuthorizer added in v0.1.1

type OAuthAuthorizer interface {
	AuthorizationURL(OAuthAuthorizationRequest) (string, error)
	ExchangeAuthorizationCode(context.Context, OAuthCodeExchangeRequest) (OAuthTokens, error)
}

OAuthAuthorizer is an optional account-authorization protocol capability, not a model-callable business operation. Integration owns the session, current-user authorization, exact redirect allowlist, state, PKCE, one-time code consumption, encrypted token persistence and recovery. Providers perform protocol I/O only through the host Transport. Hosts must never blindly retry an uncertain exchange.

func ResolveOAuthAuthorizer added in v0.1.1

func ResolveOAuthAuthorizer(adapter Adapter) (OAuthAuthorizer, bool)

type OAuthCodeExchangeRequest added in v0.1.1

type OAuthCodeExchangeRequest struct {
	Connection      Connection `json:"connection"`
	ClientID        string     `json:"-"`
	ClientSecret    string     `json:"-"`
	RedirectURI     string     `json:"redirect_uri"`
	RequestedScopes []string   `json:"requested_scopes"`
	Code            string     `json:"-"`
	CodeVerifier    string     `json:"-"`
}

type OAuthConnectionTestScopeProvider added in v0.1.1

type OAuthConnectionTestScopeProvider interface {
	OAuthConnectionTestScopes() (alternatives [][]string, declared bool)
}

OAuthConnectionTestScopeProvider declares the OAuth scopes needed by the provider's fixed connection probe. Alternatives are ORed; every scope in an alternative is required. A missing declaration is distinct from a declared empty alternative (no scopes required). This never adds requested scopes or grants business access. Registry registration snapshots this metadata.

type OAuthOperationScopeProvider added in v0.1.1

type OAuthOperationScopeProvider interface {
	OAuthOperationScopes(operationKey string) (alternatives [][]string, declared bool)
}

OAuthOperationScopeProvider declares the actual OAuth grants required by one registered operation. Alternatives are ORed, members are ANDed. The absence of a declaration must not grant account access; a declared empty alternative explicitly requires no OAuth scope. This metadata neither authorizes the caller nor changes the operation's effect. Hosts must check both separately. Registry registration snapshots declarations for descriptor operations only.

type OAuthTokens added in v0.1.1

type OAuthTokens struct {
	AccessToken      string   `json:"-"`
	RefreshToken     string   `json:"-"`
	TokenType        string   `json:"token_type"`
	GrantedScopes    []string `json:"granted_scopes"`
	ExpiresInSeconds int64    `json:"expires_in_seconds"`
}

OAuthTokens is private Provider-to-Integration output. Never serialize raw credentials into traces, model payloads or product responses. GrantedScopes record the actual response (or requested scope when omitted under RFC 6749), not product permission: hosts still intersect their current grants and policy.

type OperationDescriptor

type OperationDescriptor struct {
	ConnectorKey   string              `json:"connector_key"`
	ProviderKey    string              `json:"provider_key"`
	Key            string              `json:"key"`
	Mode           OperationMode       `json:"mode"`
	ContractSHA256 string              `json:"contract_sha256"`
	Reliability    ReliabilityContract `json:"reliability"`
}

func (OperationDescriptor) Validate

func (d OperationDescriptor) Validate() error

type OperationEffect

type OperationEffect string
const (
	EffectRead    OperationEffect = "read"
	EffectReserve OperationEffect = "reserve"
	EffectWrite   OperationEffect = "write"
)

type OperationMode

type OperationMode string
const (
	ModeCall           OperationMode = "call"
	ModeEnqueue        OperationMode = "enqueue"
	ModeStartOperation OperationMode = "start_operation"
)

type Principal

type Principal struct {
	UserID          string `json:"user_id,omitempty"`
	RoleKey         string `json:"role_key,omitempty"`
	OrgID           string `json:"org_id,omitempty"`
	RequestID       string `json:"request_id,omitempty"`
	CorrelationID   string `json:"correlation_id,omitempty"`
	CausationID     string `json:"causation_id,omitempty"`
	WorkspaceID     string `json:"workspace_id,omitempty"`
	IsAuthenticated bool   `json:"is_authenticated,omitempty"`
}

type ProcessRequest

type ProcessRequest struct {
	Executable       string        `json:"executable"`
	Arguments        []string      `json:"arguments,omitempty"`
	WorkingDirectory string        `json:"working_directory,omitempty"`
	MaxMessageBytes  int64         `json:"max_message_bytes,omitempty"`
	ShutdownGrace    time.Duration `json:"shutdown_grace,omitempty"`
}

type ProcessSession

type ProcessSession interface {
	SendLine(context.Context, []byte) error
	ReceiveLine(context.Context) ([]byte, error)
	Close(context.Context) error
}

type ProcessTransport

type ProcessTransport interface {
	StartProcess(context.Context, ProcessRequest) (ProcessSession, error)
}

ProcessTransport is an optional host-owned capability for Providers that speak a line-delimited protocol over a governed child process. The host owns executable authorization, process creation, stdio, limits, and termination.

type ProviderDescriptor

type ProviderDescriptor struct {
	ConnectorKey      string                  `json:"connector_key"`
	ProviderKey       string                  `json:"provider_key"`
	ProviderRevision  string                  `json:"provider_revision"`
	StartupActivation StartupActivationPolicy `json:"startup_activation,omitempty"`
	ConfigFields      []ConfigField           `json:"config_fields,omitempty"`
	SecretFields      []SecretField           `json:"secret_fields,omitempty"`
	Operations        []OperationDescriptor   `json:"operations"`
}

func (ProviderDescriptor) RequiresReconciler

func (d ProviderDescriptor) RequiresReconciler() bool

func (ProviderDescriptor) Validate

func (d ProviderDescriptor) Validate() error

type ProviderError

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

ProviderError carries machine-readable recovery semantics. Error deliberately returns only Code: provider response text and wrapped causes may contain credentials or customer data and are not a public/logging contract.

func (*ProviderError) Classification

func (e *ProviderError) Classification() ErrorClassification

func (*ProviderError) Code

func (e *ProviderError) Code() string

func (*ProviderError) Error

func (e *ProviderError) Error() string

func (*ProviderError) Unwrap

func (e *ProviderError) Unwrap() error

type ProviderSchema

type ProviderSchema struct {
	ConnectorKey      string                  `json:"connector_key"`
	ProviderKey       string                  `json:"provider_key"`
	ProviderRevision  string                  `json:"provider_revision"`
	StartupActivation StartupActivationPolicy `json:"startup_activation,omitempty"`
	ConfigFields      []ConfigField           `json:"config_fields,omitempty"`
	SecretFields      []SecretField           `json:"secret_fields,omitempty"`
}

func (ProviderSchema) Validate

func (s ProviderSchema) Validate() error

type ProviderSet

type ProviderSet struct {
	Providers []Adapter
}

ProviderSet is one explicit batch of Provider Adapters composed by a project before the Runtime validates and freezes its Registry.

type ProviderSetFactory

type ProviderSetFactory func(Transport) (ProviderSet, error)

ProviderSetFactory binds project Adapter constructors to the host-owned Transport before their descriptors enter the frozen Registry.

type ReconcileRequest

type ReconcileRequest struct {
	ConnectorKey   string            `json:"connector_key"`
	ProviderKey    string            `json:"provider_key"`
	OperationKey   string            `json:"operation_key"`
	ContractSHA256 string            `json:"contract_sha256"`
	Connection     Connection        `json:"connection"`
	RequestRef     string            `json:"request_ref"`
	ResponseRef    string            `json:"response_ref,omitempty"`
	Payload        json.RawMessage   `json:"payload"`
	Secrets        map[string]string `json:"secrets,omitempty"`
	Timeout        time.Duration     `json:"timeout,omitempty"`
	Principal      Principal         `json:"principal"`
}

func (ReconcileRequest) Validate

func (r ReconcileRequest) Validate() error

type ReconcileResult

type ReconcileResult struct {
	Outcome     ReconciliationOutcome `json:"outcome"`
	Result      *CallResult           `json:"result,omitempty"`
	FailureCode string                `json:"failure_code,omitempty"`
	RetryAfter  time.Duration         `json:"retry_after,omitempty"`
}

func (ReconcileResult) Validate

func (r ReconcileResult) Validate() error

type Reconciler

type Reconciler interface {
	Reconcile(context.Context, ReconcileRequest) (ReconcileResult, error)
}

Reconciler is optional and read-only. Integration invokes it only for an operation whose ReliabilityContract declares provider_lookup.

type ReconciliationMode

type ReconciliationMode string
const (
	ReconciliationNone           ReconciliationMode = "none"
	ReconciliationProviderLookup ReconciliationMode = "provider_lookup"
)

type ReconciliationOutcome

type ReconciliationOutcome string
const (
	ReconciliationSucceeded ReconciliationOutcome = "succeeded"
	ReconciliationFailed    ReconciliationOutcome = "failed"
	ReconciliationPending   ReconciliationOutcome = "pending"
	ReconciliationNotFound  ReconciliationOutcome = "not_found"
	ReconciliationUnknown   ReconciliationOutcome = "unknown"
)

type Registry

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

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Descriptors

func (r *Registry) Descriptors() []ProviderDescriptor

func (*Registry) Freeze

func (r *Registry) Freeze()

func (*Registry) Frozen

func (r *Registry) Frozen() bool

func (*Registry) Provider

func (r *Registry) Provider(connectorKey, providerKey string) (Adapter, bool)

func (*Registry) Providers

func (r *Registry) Providers() []Adapter

func (*Registry) Register

func (r *Registry) Register(provider Adapter) error

func (*Registry) RegisterProviderSet

func (r *Registry) RegisterProviderSet(set ProviderSet) error

type ReliabilityContract

type ReliabilityContract struct {
	Effect         OperationEffect      `json:"effect"`
	Idempotency    IdempotencyContract  `json:"idempotency"`
	Reconciliation ReconciliationMode   `json:"reconciliation"`
	Compensation   CompensationContract `json:"compensation"`
}

func (ReliabilityContract) Validate

func (c ReliabilityContract) Validate(operationKey string) error

type ResourceHealthReport

type ResourceHealthReport struct {
	ObservationID     string `json:"observation_id"`
	Kind              string `json:"kind"`
	State             string `json:"state"`
	PreviousState     string `json:"previous_state,omitempty"`
	EvidenceSource    string `json:"evidence_source"`
	QuotaUsedPercent  *int   `json:"quota_used_percent,omitempty"`
	BalanceBand       string `json:"balance_band,omitempty"`
	CapabilityBlocked bool   `json:"capability_blocked"`
	ObservedAt        string `json:"observed_at"`
	ErrorCode         string `json:"error_code,omitempty"`
}

ResourceHealthReport is an optional, provider-normalized observation. A provider that lacks a reliable API or explicit provider error must omit it; Integration never infers quota or billing state from a generic failed call.

type SMTPRequest

type SMTPRequest struct {
	Host           string        `json:"host"`
	Port           int           `json:"port"`
	ImplicitTLS    bool          `json:"implicit_tls,omitempty"`
	StartTLS       bool          `json:"start_tls,omitempty"`
	TLSServerName  string        `json:"tls_server_name,omitempty"`
	TLSCAPEM       string        `json:"tls_ca_pem,omitempty"`
	Username       string        `json:"username,omitempty"`
	SecretPassword string        `json:"-"`
	EnvelopeFrom   string        `json:"envelope_from,omitempty"`
	Recipients     []string      `json:"recipients,omitempty"`
	Message        []byte        `json:"message,omitempty"`
	ProbeOnly      bool          `json:"probe_only,omitempty"`
	Timeout        time.Duration `json:"timeout,omitempty"`
}

type SMTPResult

type SMTPResult struct {
	Connected bool `json:"connected"`
	Accepted  bool `json:"accepted"`
}

type SMTPTransport

type SMTPTransport interface {
	SendSMTP(context.Context, SMTPRequest) (SMTPResult, error)
}

SMTPTransport is an optional host-owned capability for Providers that deliver RFC 5322 messages. Keeping it separate preserves compatibility for transports that only support HTTP and SQL.

type SQLOperation

type SQLOperation string
const (
	SQLOperationPing  SQLOperation = "ping"
	SQLOperationQuery SQLOperation = "query"
	SQLOperationExec  SQLOperation = "exec"
)

type SQLRequest

type SQLRequest struct {
	Driver    string        `json:"driver"`
	DSN       string        `json:"-"`
	Operation SQLOperation  `json:"operation"`
	Statement string        `json:"statement,omitempty"`
	Arguments []any         `json:"arguments,omitempty"`
	MaxRows   int           `json:"max_rows,omitempty"`
	Timeout   time.Duration `json:"timeout,omitempty"`
}

type SQLResult

type SQLResult struct {
	Columns      []string `json:"columns,omitempty"`
	Rows         [][]any  `json:"rows,omitempty"`
	RowsAffected int64    `json:"rows_affected,omitempty"`
	LastInsertID *int64   `json:"last_insert_id,omitempty"`
	Truncated    bool     `json:"truncated,omitempty"`
}

type SecretCredentialKind

type SecretCredentialKind string
const (
	SecretCredentialAPIKey            SecretCredentialKind = "api_key"
	SecretCredentialBasicAuthPassword SecretCredentialKind = "basic_auth_password"
	SecretCredentialBearerToken       SecretCredentialKind = "bearer_token"
	SecretCredentialCertificate       SecretCredentialKind = "certificate"
	SecretCredentialConnectionString  SecretCredentialKind = "connection_string"
	SecretCredentialDatabasePassword  SecretCredentialKind = "database_password"
	SecretCredentialGeneric           SecretCredentialKind = "generic_secret"
	SecretCredentialIdentifier        SecretCredentialKind = "identifier"
	SecretCredentialOAuthClientSecret SecretCredentialKind = "oauth_client_secret"
	SecretCredentialPrivateKey        SecretCredentialKind = "private_key"
	SecretCredentialRefreshToken      SecretCredentialKind = "refresh_token"
	SecretCredentialServiceAccount    SecretCredentialKind = "service_account"
	SecretCredentialSigningSecret     SecretCredentialKind = "signing_secret"
)

type SecretExpiryPolicy

type SecretExpiryPolicy string
const (
	SecretExpiryNone     SecretExpiryPolicy = "none"
	SecretExpiryOptional SecretExpiryPolicy = "optional"
	SecretExpiryRequired SecretExpiryPolicy = "required"
)

type SecretField

type SecretField struct {
	Key             string                       `json:"key"`
	Name            string                       `json:"name"`
	Description     string                       `json:"description,omitempty"`
	I18n            map[string]FieldLocalization `json:"i18n,omitempty"`
	Required        bool                         `json:"required"`
	CredentialKind  SecretCredentialKind         `json:"credential_kind"`
	MaterialFormat  SecretMaterialFormat         `json:"material_format"`
	RotationPolicy  SecretRotationPolicy         `json:"rotation_policy"`
	ExpiryPolicy    SecretExpiryPolicy           `json:"expiry_policy"`
	TestRequirement SecretTestRequirement        `json:"test_requirement"`
}

type SecretMaterialFormat

type SecretMaterialFormat string
const (
	SecretMaterialOpaque         SecretMaterialFormat = "opaque"
	SecretMaterialText           SecretMaterialFormat = "text"
	SecretMaterialJSONObject     SecretMaterialFormat = "json_object"
	SecretMaterialPEM            SecretMaterialFormat = "pem"
	SecretMaterialPEMOrOpaque    SecretMaterialFormat = "pem_or_opaque"
	SecretMaterialPEMOrReference SecretMaterialFormat = "pem_or_reference"
	SecretMaterialURIOrDSN       SecretMaterialFormat = "uri_or_dsn"
)

type SecretRotationPolicy

type SecretRotationPolicy string
const (
	SecretRotationManual       SecretRotationPolicy = "manual"
	SecretRotationOAuthRefresh SecretRotationPolicy = "oauth_refresh"
)

type SecretTestRequirement

type SecretTestRequirement string
const (
	SecretTestOptional  SecretTestRequirement = "optional"
	SecretTestWhenBound SecretTestRequirement = "when_bound"
)

type StartOperation

type StartOperation[I any] struct {
	ConnectorKey   string
	ProviderKey    string
	Key            string
	ContractSHA256 string
	Reliability    ReliabilityContract
}

StartOperation describes asynchronous delivery that starts a long-running external operation. Integration owns the local durable operation identity.

func (StartOperation[I]) Descriptor

func (o StartOperation[I]) Descriptor() OperationDescriptor

type StartupActivationPolicy

type StartupActivationPolicy string
const (
	StartupActivationManual      StartupActivationPolicy = ""
	StartupActivationDefaultSafe StartupActivationPolicy = "default_safe"
)

type TestConnectionRequest

type TestConnectionRequest struct {
	ConnectorKey string            `json:"connector_key"`
	ProviderKey  string            `json:"provider_key"`
	Connection   Connection        `json:"connection"`
	Secrets      map[string]string `json:"secrets,omitempty"`
	Timeout      time.Duration     `json:"timeout,omitempty"`
	Principal    Principal         `json:"principal"`
}

TestConnectionRequest is a management-plane probe envelope. It deliberately has no operation key or payload: testing a configured connection is not a business operation and must not be disguised as Adapter.Call.

type TestConnectionResult

type TestConnectionResult struct {
	Connected     bool              `json:"connected"`
	Details       json.RawMessage   `json:"details,omitempty"`
	SecretUpdates map[string]string `json:"secret_updates,omitempty"`
}

type Transport

type Transport interface {
	RoundTripHTTP(context.Context, HTTPRequest) (HTTPResponse, error)
	ExecuteSQL(context.Context, SQLRequest) (SQLResult, error)
}

Transport is the only outbound I/O capability supplied to project-owned Connector Adapters. The deployment host owns the concrete clients, pools and limits.

type TypedRequest

type TypedRequest[I any] struct {
	Input      I
	Connection Connection
	RequestRef string
	Headers    map[string]string
	Secrets    map[string]string
	Delivery   bool
	Principal  Principal
}

type TypedResult

type TypedResult[O any] struct {
	Output         O
	ResponseRef    string
	SecretUpdates  map[string]string
	ResourceHealth *ResourceHealthReport
}

type VerifiedWebhook

type VerifiedWebhook struct {
	EventType        string                   `json:"event_type"`
	ExternalID       string                   `json:"external_id"`
	Payload          json.RawMessage          `json:"payload"`
	Security         *WebhookSecurityEvidence `json:"security,omitempty"`
	Challenge        string                   `json:"challenge,omitempty"`
	ChallengeFormat  string                   `json:"challenge_format,omitempty"`
	ExternalIdentity *WebhookExternalIdentity `json:"external_identity,omitempty"`
	DeliveryReceipt  *WebhookDeliveryReceipt  `json:"delivery_receipt,omitempty"`
}

type VerifyWebhookRequest

type VerifyWebhookRequest struct {
	ConnectorKey string              `json:"connector_key"`
	ProviderKey  string              `json:"provider_key"`
	Connection   Connection          `json:"connection"`
	Headers      map[string][]string `json:"headers,omitempty"`
	Query        map[string][]string `json:"query,omitempty"`
	Secrets      map[string]string   `json:"secrets,omitempty"`
	Body         []byte              `json:"body"`
	ReceivedAt   time.Time           `json:"received_at"`
}

type WebhookDeliveryReceipt

type WebhookDeliveryReceipt struct {
	ResponseRef string    `json:"response_ref,omitempty"`
	Status      string    `json:"status,omitempty"`
	Error       string    `json:"error,omitempty"`
	OccurredAt  time.Time `json:"occurred_at,omitempty"`
}

type WebhookExternalIdentity

type WebhookExternalIdentity struct {
	Subject     string `json:"subject"`
	SubjectType string `json:"subject_type,omitempty"`
	Name        string `json:"name,omitempty"`
	Group       string `json:"group,omitempty"`
}

type WebhookSecurityEvidence

type WebhookSecurityEvidence struct {
	SignatureVerified bool      `json:"signature_verified"`
	Nonce             string    `json:"nonce,omitempty"`
	DeviceIdentity    string    `json:"device_identity,omitempty"`
	EventTime         time.Time `json:"event_time,omitempty"`
}

type WebhookVerifier

type WebhookVerifier interface {
	VerifyWebhook(context.Context, VerifyWebhookRequest) (VerifiedWebhook, error)
}

WebhookVerifier is optional. Integration owns the HTTP route, request limits, replay/idempotency checks and persistence; providers only authenticate and normalize one already-resolved connection's inbound request.

Directories

Path Synopsis
Package calendar defines provider-neutral read contracts.
Package calendar defines provider-neutral read contracts.
Package calendarwrite defines bounded calendar mutation contracts.
Package calendarwrite defines bounded calendar mutation contracts.
Package contracttest provides reusable, side-effect-free checks for Connector implementations.
Package contracttest provides reusable, side-effect-free checks for Connector implementations.
examples
minimal
Package minimal demonstrates a Connector that performs no network access.
Package minimal demonstrates a Connector that performs no network access.
Package mail defines bounded, provider-neutral mailbox read contracts.
Package mail defines bounded, provider-neutral mailbox read contracts.
Package mailwrite defines explicit, bounded outgoing mail contracts.
Package mailwrite defines explicit, bounded outgoing mail contracts.
Package mcptool owns the public Connector operation contract used to list and invoke tools on an MCP server.
Package mcptool owns the public Connector operation contract used to list and invoke tools on an MCP server.
Package web defines bounded public-web search and page-read contracts.
Package web defines bounded public-web search and page-read contracts.

Jump to

Keyboard shortcuts

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