bridgesdk

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package bridgesdk provides the shared provider-runtime substrate for bridge adapters. It owns provider-scoped boot, Host API access, managed-instance caching, ingress hardening, batching, deduplication, recovery helpers, and lifecycle primitives so providers can focus on platform-specific mapping.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InboundBatchKey

func InboundBatchKey(envelope bridgepkg.InboundMessageEnvelope) string

InboundBatchKey derives the stable routing-identity key used for batching.

func NewWebhookHandler

func NewWebhookHandler(config WebhookGuardConfig, next WebhookHandler) (http.Handler, error)

NewWebhookHandler constructs the shared ingress-hardening handler.

func RetryDo

func RetryDo[T any](ctx context.Context, config RetryConfig, fn func(context.Context) (T, error)) (T, error)

RetryDo retries the operation according to the shared classification policy.

func TargetSnapshotsFromManagedInstances

func TargetSnapshotsFromManagedInstances(
	ctx context.Context,
	session *Session,
	req bridgepkg.BridgeTargetSnapshotRequest,
) ([]bridgepkg.BridgeTargetSnapshot, error)

TargetSnapshotsFromManagedInstances derives a conservative target directory from daemon-provided managed-instance delivery defaults. Providers with native directory APIs can override RuntimeConfig.TargetSnapshots.

Types

type AuthError

type AuthError struct {
	Err error
}

AuthError marks an authentication failure explicitly.

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

type CallFunc

type CallFunc func(context.Context, string, any, any) error

CallFunc issues one typed Host API request.

type ClassifiedError

type ClassifiedError struct {
	Class      ErrorClass
	Err        error
	RetryAfter time.Duration
	Message    string
}

ClassifiedError is one actionable provider failure classification.

func ClassifyError

func ClassifyError(err error) ClassifiedError

ClassifyError maps one provider failure into the shared recovery classes.

func (ClassifiedError) Recovery

func (c ClassifiedError) Recovery() RecoveryDecision

Recovery maps the classified provider failure into runtime actions.

type DedupCache

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

DedupCache is the adapter-local TTL cache used to suppress immediate platform retries.

func NewDedupCache

func NewDedupCache(ttl time.Duration, maxSize int) *DedupCache

NewDedupCache constructs a TTL-based dedup cache.

func (*DedupCache) Clear

func (c *DedupCache) Clear()

Clear removes every tracked idempotency key.

func (*DedupCache) Mark

func (c *DedupCache) Mark(key string) bool

Mark returns true when the idempotency key is already active within the TTL window.

func (*DedupCache) Seen

func (c *DedupCache) Seen(key string) bool

Seen reports whether the idempotency key is already active within the TTL window without recording it.

type DeliveryHandler

DeliveryHandler handles one daemon-originated `bridges/deliver` request.

type ErrorClass

type ErrorClass string

ErrorClass is the shared bridge-sdk provider failure classification.

const (
	ErrorClassAuth      ErrorClass = "auth"
	ErrorClassRateLimit ErrorClass = "rate_limit"
	ErrorClassTimeout   ErrorClass = "timeout"
	ErrorClassTransient ErrorClass = "transient"
	ErrorClassPermanent ErrorClass = "permanent"
)

type FixedWindowRateLimiter

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

FixedWindowRateLimiter applies a simple fixed-window request limit per key.

func NewFixedWindowRateLimiter

func NewFixedWindowRateLimiter(limit int, window time.Duration) *FixedWindowRateLimiter

NewFixedWindowRateLimiter constructs a new fixed-window limiter.

func (*FixedWindowRateLimiter) Allow

func (l *FixedWindowRateLimiter) Allow(key string) bool

Allow reports whether another request may proceed for the key.

type HTTPError

type HTTPError struct {
	StatusCode int
	Message    string
	RetryAfter time.Duration
}

HTTPError captures provider HTTP failures with optional Retry-After guidance.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type HealthHandler

type HealthHandler func(context.Context, *Session) error

HealthHandler handles one daemon health-check probe.

type HostAPIClient

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

HostAPIClient is the typed provider-side client for bridge Host API calls.

func NewHostAPIClient

func NewHostAPIClient(peer *Peer) *HostAPIClient

NewHostAPIClient constructs a Host API client over the shared runtime peer.

func NewHostAPIClientFromCall

func NewHostAPIClientFromCall(call CallFunc) *HostAPIClient

NewHostAPIClientFromCall constructs a Host API client from an arbitrary call function, mainly for tests.

func (*HostAPIClient) Call

func (c *HostAPIClient) Call(ctx context.Context, method string, params any, result any) error

Call issues one raw Host API request.

func (*HostAPIClient) GetBridgeInstance

func (c *HostAPIClient) GetBridgeInstance(
	ctx context.Context,
	bridgeInstanceID string,
) (*bridgepkg.BridgeInstance, error)

GetBridgeInstance returns one provider-owned bridge instance.

func (*HostAPIClient) IngestBridgeMessage

IngestBridgeMessage ingests one normalized inbound bridge event.

func (*HostAPIClient) ListBridgeInstances

func (c *HostAPIClient) ListBridgeInstances(ctx context.Context) ([]bridgepkg.BridgeInstance, error)

ListBridgeInstances returns every bridge instance currently assigned to the provider runtime.

func (*HostAPIClient) ReportBridgeInstanceState

ReportBridgeInstanceState reports one provider-observed bridge status change.

type InFlightLimiter

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

InFlightLimiter bounds concurrent webhook requests.

func NewInFlightLimiter

func NewInFlightLimiter(limit int) *InFlightLimiter

NewInFlightLimiter constructs a new in-flight semaphore.

func (*InFlightLimiter) Release

func (l *InFlightLimiter) Release()

Release frees one in-flight slot.

func (*InFlightLimiter) TryAcquire

func (l *InFlightLimiter) TryAcquire() bool

TryAcquire attempts to reserve one in-flight slot.

type InboundBatch

type InboundBatch struct {
	Key       string                             `json:"key"`
	Items     []bridgepkg.InboundMessageEnvelope `json:"items"`
	CreatedAt time.Time                          `json:"created_at"`
	UpdatedAt time.Time                          `json:"updated_at"`
}

InboundBatch groups a short burst of inbound bridge envelopes under one routing identity.

type InboundBatchDispatch

type InboundBatchDispatch func(context.Context, InboundBatch) error

InboundBatchDispatch handles one flushed inbound batch.

type InboundBatcher

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

InboundBatcher coalesces rapid-fire inbound envelopes under one routing identity.

func NewInboundBatcher

func NewInboundBatcher(config InboundBatcherConfig) (*InboundBatcher, error)

NewInboundBatcher constructs the debounce-based inbound batcher.

func (*InboundBatcher) Close

func (b *InboundBatcher) Close()

Close stops the batcher and cancels any unflushed pending batches.

func (*InboundBatcher) Enqueue

Enqueue appends one inbound envelope to the routing-identity batch.

func (*InboundBatcher) FlushAll

func (b *InboundBatcher) FlushAll(ctx context.Context) error

FlushAll flushes every pending batch immediately.

type InboundBatcherConfig

type InboundBatcherConfig struct {
	Context        context.Context
	Delay          time.Duration
	SplitDelay     time.Duration
	SplitThreshold int
	Dispatch       InboundBatchDispatch
	Now            func() time.Time
}

InboundBatcherConfig configures the debounce-based inbound batcher.

type InitializeHandler

type InitializeHandler func(context.Context, *Session) error

InitializeHandler runs after the provider runtime receives the negotiated initialize request and seeds its Host API client and managed-instance cache.

type InstanceCache

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

InstanceCache keeps the provider-owned managed-instance snapshot locally, preserving launch-time bound secret material across Host API syncs.

func NewInstanceCache

func NewInstanceCache(runtime *subprocess.InitializeBridgeRuntime) *InstanceCache

NewInstanceCache constructs a cache seeded from the negotiated bridge runtime.

func (*InstanceCache) BoundSecretValue

func (c *InstanceCache) BoundSecretValue(instanceID string, bindingName string) (string, bool)

BoundSecretValue returns one launch-time bound secret value for the managed instance.

func (*InstanceCache) Get

Get returns one managed instance snapshot by id.

func (*InstanceCache) List

List returns every managed instance snapshot in stable id order.

func (*InstanceCache) Reset

Reset replaces the managed-instance snapshot with the provided runtime grant.

func (*InstanceCache) Snapshot

Snapshot returns the current managed-runtime snapshot.

func (*InstanceCache) Sync

Sync refreshes the provider-owned instance state from the Host API while preserving launch-time bound secrets for instances that were already hydrated at initialize time.

type Peer

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

Peer is the bridge-sdk JSON-RPC transport used by provider runtimes to receive daemon requests and issue Host API calls over the same stdio stream.

func NewPeer

func NewPeer(stdin io.Reader, stdout io.Writer) *Peer

NewPeer constructs a JSON-RPC peer bound to the provided reader and writer.

func (*Peer) Call

func (p *Peer) Call(ctx context.Context, method string, params any, result any) error

Call issues one outbound JSON-RPC request and decodes the typed result.

func (*Peer) Handle

func (p *Peer) Handle(method string, handler RPCHandler) error

Handle registers one inbound method handler.

func (*Peer) Serve

func (p *Peer) Serve(ctx context.Context) error

Serve runs the peer read loop until EOF or a transport error occurs.

type PermanentError

type PermanentError struct {
	Err error
}

PermanentError marks a non-retryable provider failure explicitly.

func (*PermanentError) Error

func (e *PermanentError) Error() string

func (*PermanentError) Unwrap

func (e *PermanentError) Unwrap() error

type RPCHandler

type RPCHandler func(context.Context, json.RawMessage) (any, error)

RPCHandler handles one inbound JSON-RPC request.

type RateLimitError

type RateLimitError struct {
	Err        error
	RetryAfter time.Duration
}

RateLimitError marks a rate-limit failure explicitly.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

type RecoveryDecision

type RecoveryDecision struct {
	Retry       bool
	RetryAfter  time.Duration
	Status      bridgepkg.BridgeStatus
	Degradation *bridgepkg.BridgeDegradation
}

RecoveryDecision is the runtime action derived from one classified error.

type RetryConfig

type RetryConfig struct {
	Attempts  int
	MinDelay  time.Duration
	MaxDelay  time.Duration
	Jitter    float64
	RandFloat func() float64
	OnRetry   func(attempt int, maxAttempts int, classified ClassifiedError)
}

RetryConfig configures the jittered backoff retry helper.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns the bridge-sdk default retry policy.

type Runtime

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

Runtime is the shared provider runtime scaffold built on the bridge SDK.

func NewRuntime

func NewRuntime(config RuntimeConfig) (*Runtime, error)

NewRuntime constructs the shared provider runtime scaffold.

func (*Runtime) Serve

func (r *Runtime) Serve(ctx context.Context, stdin io.Reader, stdout io.Writer) error

Serve runs the provider runtime over the supplied stdio transport.

func (*Runtime) Session

func (r *Runtime) Session() *Session

Session returns the negotiated runtime session once initialize succeeds.

type RuntimeConfig

type RuntimeConfig struct {
	ExtensionInfo   subprocess.InitializeExtensionInfo
	Initialize      InitializeHandler
	Deliver         DeliveryHandler
	TargetSnapshots TargetSnapshotHandler
	HealthCheck     HealthHandler
	Shutdown        ShutdownHandler
	Now             func() time.Time
}

RuntimeConfig configures the shared provider runtime scaffold.

type Session

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

Session captures the negotiated provider runtime session state.

func (*Session) AckDelivery

func (s *Session) AckDelivery(
	req bridgepkg.DeliveryRequest,
	remoteMessageID string,
	replaceRemoteMessageID string,
) (bridgepkg.DeliveryAck, error)

AckDelivery builds and validates one delivery acknowledgement for the request.

func (*Session) BridgeRuntime

func (s *Session) BridgeRuntime() *subprocess.InitializeBridgeRuntime

BridgeRuntime returns the current managed-instance runtime snapshot.

func (*Session) Cache

func (s *Session) Cache() *InstanceCache

Cache returns the provider-owned managed-instance cache.

func (*Session) HostAPI

func (s *Session) HostAPI() *HostAPIClient

HostAPI returns the typed bridge Host API client.

func (*Session) InitializeRequest

func (s *Session) InitializeRequest() subprocess.InitializeRequest

InitializeRequest returns a clone of the negotiated initialize request.

func (*Session) InitializeResponse

func (s *Session) InitializeResponse() subprocess.InitializeResponse

InitializeResponse returns a copy of the initialize response sent by the runtime.

func (*Session) ReportClassifiedError

func (s *Session) ReportClassifiedError(
	ctx context.Context,
	bridgeInstanceID string,
	classified ClassifiedError,
) (*bridgepkg.BridgeInstance, RecoveryDecision, error)

ReportClassifiedError applies the recovery mapping for one provider failure and reports the resulting instance status transition through the Host API.

func (*Session) SyncInstances

SyncInstances refreshes the managed-instance cache from the Host API.

type ShutdownHandler

type ShutdownHandler func(context.Context, *Session, subprocess.ShutdownRequest) error

ShutdownHandler handles one daemon-originated cooperative shutdown request.

type SignatureVerifier

type SignatureVerifier func(context.Context, *http.Request, []byte) error

SignatureVerifier validates the raw webhook request body before provider mapping runs.

type TargetSnapshotHandler

TargetSnapshotHandler handles one daemon-originated bridge target discovery request.

type TransientError

type TransientError struct {
	Err error
}

TransientError marks a retryable provider failure explicitly.

func (*TransientError) Error

func (e *TransientError) Error() string

func (*TransientError) Unwrap

func (e *TransientError) Unwrap() error

type WebhookGuardConfig

type WebhookGuardConfig struct {
	AllowedMethods      []string
	AllowedContentTypes []string
	MaxBodyBytes        int64
	RateLimiter         *FixedWindowRateLimiter
	InFlightLimiter     *InFlightLimiter
	VerifySignature     SignatureVerifier
	RequestKey          func(*http.Request) string
	Now                 func() time.Time
}

WebhookGuardConfig configures the shared ingress hardening pipeline.

type WebhookHandler

type WebhookHandler func(http.ResponseWriter, *http.Request, WebhookRequest) error

WebhookHandler receives the guarded webhook request after the shared ingress checks have passed.

type WebhookRequest

type WebhookRequest struct {
	Body       []byte
	ReceivedAt time.Time
}

WebhookRequest is the provider-facing request payload after ingress guards complete.

Jump to

Keyboard shortcuts

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