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
- Variables
- func ApplyParentMessage(envelope *bridgepkg.InboundMessageEnvelope, message ParentMessage)
- func ChunkMessage(text string, limit int, lenFn func(string) int) []string
- func CredentialedHTTPClient(base *http.Client) *http.Client
- func DecodeSingleJSONValue(reader io.Reader, destination any) error
- func DrainAndCloseHTTPResponseBody(body io.ReadCloser) error
- func FinalizeHTTPResponseBody(body io.ReadCloser, operationErr error, ...) error
- func InboundBatchKey(envelope bridgepkg.InboundMessageEnvelope) string
- func IsCommittedMutation(err error) bool
- func Main(providerName string, serve ProviderServeFunc)
- func MarkCommittedMutation(err error) error
- func NewWebhookHandler(config WebhookGuardConfig, next WebhookHandler) (http.Handler, error)
- func ProviderIdentityCheckRecord(err error, secretBindings ...string) bridgepkg.BridgeCheckRecord
- func ReadHTTPResponseBody(reader io.Reader) (string, error)
- func RetryDo[T any](ctx context.Context, config RetryConfig, fn func(context.Context) (T, error)) (T, error)
- func RunProviderCommand(providerName string, args []string, stdin io.Reader, stdout io.Writer, ...) error
- func ShouldContinueTextDeliveryAfterProgress(err error) bool
- func TargetSnapshotsFromManagedInstances(ctx context.Context, session *Session, ...) ([]bridgepkg.BridgeTargetSnapshot, error)
- func UTF16Len(value string) int
- func WebhookCheckRecords(ctx context.Context, instance bridgepkg.BridgeInstance, doer webhookHTTPDoer) []bridgepkg.BridgeCheckRecord
- type AdapterMarkerPaths
- type AdapterMarkers
- func (m *AdapterMarkers) Error() error
- func (m *AdapterMarkers) RecordCrash(value any)
- func (m *AdapterMarkers) RecordDelivery(marker DeliveryMarker)
- func (m *AdapterMarkers) RecordIngest(marker IngestMarker)
- func (m *AdapterMarkers) RecordInitialize(marker *InitializeMarker)
- func (m *AdapterMarkers) RecordListen(address string)
- func (m *AdapterMarkers) RecordOwnership(marker OwnershipMarker)
- func (m *AdapterMarkers) RecordShutdown(pid int)
- func (m *AdapterMarkers) RecordStart(pid int)
- func (m *AdapterMarkers) RecordState(marker StateMarker)
- func (m *AdapterMarkers) ReportError(action string, err error)
- func (m *AdapterMarkers) ShouldCrashOnce() bool
- type AuthError
- type CallFunc
- type CheckHandler
- type ClassifiedError
- type CommittedMutationError
- type DedupCache
- type DeliveryChunkCursor
- type DeliveryChunkMode
- type DeliveryHandler
- type DeliveryMarker
- type DeliveryStateStore
- func (s *DeliveryStateStore[S]) Delete(deliveryID string) (S, bool)
- func (s *DeliveryStateStore[S]) Drain() map[string]S
- func (s *DeliveryStateStore[S]) Load(deliveryID string) (S, bool)
- func (s *DeliveryStateStore[S]) Store(deliveryID string, state S)
- func (s *DeliveryStateStore[S]) TransformAll(transform func(string, S) S) map[string]S
- func (s *DeliveryStateStore[S]) Update(deliveryID string, update func(S) S) bool
- func (s *DeliveryStateStore[S]) UpdateOrCreate(deliveryID string, resolve func(S, bool) S) (S, bool)
- type DeliveryStateStoreOption
- type ErrorClass
- type FixedWindowRateLimiter
- type HTTPError
- type HTTPResponseCommitEvidence
- type HTTPResponseCommitPolicy
- type HealthHandler
- type HostAPIClient
- func (c *HostAPIClient) Call(ctx context.Context, method string, params any, result any) error
- func (c *HostAPIClient) GetBridgeInstance(ctx context.Context, bridgeInstanceID string) (*bridgepkg.BridgeInstance, error)
- func (c *HostAPIClient) IngestBridgeMessage(ctx context.Context, envelope bridgepkg.InboundMessageEnvelope) (*bridgepkg.BridgesMessagesIngestResult, error)
- func (c *HostAPIClient) ListBridgeInstances(ctx context.Context) ([]bridgepkg.BridgeInstance, error)
- func (c *HostAPIClient) ReportBridgeInstanceState(ctx context.Context, params bridgepkg.BridgesInstancesReportStateParams) (*bridgepkg.BridgeInstance, error)
- type InFlightLimiter
- type InboundBatch
- type InboundBatchDispatch
- type InboundBatcher
- type InboundBatcherConfig
- type IngestMarker
- type InitializeHandler
- type InitializeMarker
- type InstanceCache
- func (c *InstanceCache) BoundSecretValue(instanceID string, bindingName string) (string, bool)
- func (c *InstanceCache) BoundSecretValueForProfile(profileID string, instanceID string, bindingName string) (string, bool)
- func (c *InstanceCache) Get(id string) (*subprocess.InitializeBridgeManagedInstance, bool)
- func (c *InstanceCache) GetForProfile(profileID string, instanceID string) (*subprocess.InitializeBridgeManagedInstance, bool)
- func (c *InstanceCache) List() []subprocess.InitializeBridgeManagedInstance
- func (c *InstanceCache) Reset(runtime *subprocess.InitializeBridgeRuntime)
- func (c *InstanceCache) Snapshot() *subprocess.InitializeBridgeRuntime
- func (c *InstanceCache) Sync(ctx context.Context, host *HostAPIClient) ([]subprocess.InitializeBridgeManagedInstance, error)
- type ManagedConfigPrepare
- type ManagedConfigReconciler
- type ManagedConfigResolver
- type OwnershipMarker
- type ParentMessage
- type ParentMessageCache
- func (c *ParentMessageCache) Delete(key ParentMessageKey)
- func (c *ParentMessageCache) EnrichReply(envelope *bridgepkg.InboundMessageEnvelope, parentMessageID string) bool
- func (c *ParentMessageCache) Get(key ParentMessageKey) (ParentMessage, bool)
- func (c *ParentMessageCache) Put(key ParentMessageKey, message ParentMessage)
- func (c *ParentMessageCache) RememberEnvelope(envelope bridgepkg.InboundMessageEnvelope)
- func (c *ParentMessageCache) RememberParent(envelope bridgepkg.InboundMessageEnvelope, parentMessageID string, ...)
- type ParentMessageKey
- type Peer
- type PermanentError
- type ProgressAccumulator
- type ProgressCancel
- type ProgressConfig
- type ProgressDispatcher
- func (d *ProgressDispatcher) Close()
- func (d *ProgressDispatcher) Flush(ctx context.Context) error
- func (d *ProgressDispatcher) LastAsyncError() error
- func (d *ProgressDispatcher) OnContent(ctx context.Context) error
- func (d *ProgressDispatcher) OnProgress(ctx context.Context, event bridgepkg.ToolProgress) error
- type ProgressDispatcherOption
- type ProgressHandler
- type ProgressSchedule
- type ProgressSink
- type ProviderHTTPConfig
- type ProviderHTTPServer
- type ProviderHost
- func (h *ProviderHost) ForgetStatus(bridgeInstanceID string)
- func (h *ProviderHost) GetOwnedInstance(ctx context.Context, session ProviderHostSession, bridgeInstanceID string) (*bridgepkg.BridgeInstance, error)
- func (h *ProviderHost) IngestBridgeMessage(ctx context.Context, session ProviderHostSession, ...) (*bridgepkg.BridgesMessagesIngestResult, error)
- func (h *ProviderHost) ReportReadyIfNeeded(ctx context.Context, session ProviderHostSession, bridgeInstanceID string) error
- func (h *ProviderHost) ReportState(ctx context.Context, session ProviderHostSession, bridgeInstanceID string, ...) error
- func (h *ProviderHost) Retry(ctx context.Context, call func(context.Context) error) error
- func (h *ProviderHost) Statuses() map[string]bridgepkg.BridgeStatus
- func (h *ProviderHost) SyncOwnedInstances(ctx context.Context, session ProviderHostSession) ([]subprocess.InitializeBridgeManagedInstance, error)
- type ProviderHostOption
- type ProviderHostSession
- type ProviderInitialState
- type ProviderLifecycle
- func (l *ProviderLifecycle) ClearError()
- func (l *ProviderLifecycle) Context() context.Context
- func (l *ProviderLifecycle) Go(run func()) bool
- func (l *ProviderLifecycle) Health() error
- func (l *ProviderLifecycle) Host() *ProviderHost
- func (l *ProviderLifecycle) Initialize(ctx context.Context, session *Session) error
- func (l *ProviderLifecycle) Initialized() <-chan struct{}
- func (l *ProviderLifecycle) MarkRoutesReady()
- func (l *ProviderLifecycle) RoutesReady() <-chan struct{}
- func (l *ProviderLifecycle) Serve(ctx context.Context, runtime *Runtime, stdin io.Reader, stdout io.Writer) error
- func (l *ProviderLifecycle) Session() *Session
- func (l *ProviderLifecycle) SetError(err error)
- func (l *ProviderLifecycle) Shutdown(ctx context.Context, _ *Session, request subprocess.ShutdownRequest) error
- func (l *ProviderLifecycle) Stop()
- func (l *ProviderLifecycle) StopChannel() <-chan struct{}
- func (l *ProviderLifecycle) Stopped() bool
- func (l *ProviderLifecycle) Wait(ctx context.Context) error
- type ProviderLifecycleConfig
- type ProviderReconcileFunc
- type ProviderServeFunc
- type RPCHandler
- type RateLimitError
- type RecoveryDecision
- type RetryAttempt
- type RetryBackoff
- type RetryConfig
- type RouteMergeFunc
- type RoutePathFunc
- type RouteTable
- func (t *RouteTable[C]) ByPath(path string) []C
- func (t *RouteTable[C]) Get(instanceID string) (C, bool)
- func (t *RouteTable[C]) Replace(next map[string]C, merge RouteMergeFunc[C]) []C
- func (t *RouteTable[C]) ReplaceWithCleanup(next map[string]C, merge RouteMergeFunc[C], cleanup func(C) error) error
- func (t *RouteTable[C]) Snapshot() map[string]C
- func (t *RouteTable[C]) Update(instanceID string, update func(C) C) bool
- func (t *RouteTable[C]) Wait(ctx context.Context, instanceID string, timeout time.Duration, ...) (C, bool, error)
- type Runtime
- type RuntimeConfig
- type Session
- func (s *Session) AckCommittedResultUnavailable(req bridgepkg.DeliveryRequest, reason string) (bridgepkg.DeliveryAck, error)
- func (s *Session) AckDelivery(req bridgepkg.DeliveryRequest, remoteMessageID string, ...) (bridgepkg.DeliveryAck, error)
- func (s *Session) BridgeRuntime() *subprocess.InitializeBridgeRuntime
- func (s *Session) Cache() *InstanceCache
- func (s *Session) CachedInstances() []subprocess.InitializeBridgeManagedInstance
- func (s *Session) GetBridgeInstance(ctx context.Context, bridgeInstanceID string) (*bridgepkg.BridgeInstance, error)
- func (s *Session) HostAPI() *HostAPIClient
- func (s *Session) IngestBridgeMessage(ctx context.Context, envelope bridgepkg.InboundMessageEnvelope) (*bridgepkg.BridgesMessagesIngestResult, error)
- func (s *Session) InitializeRequest() subprocess.InitializeRequest
- func (s *Session) InitializeResponse() subprocess.InitializeResponse
- func (s *Session) ReportBridgeInstanceState(ctx context.Context, params bridgepkg.BridgesInstancesReportStateParams) (*bridgepkg.BridgeInstance, error)
- func (s *Session) ReportClassifiedError(ctx context.Context, bridgeInstanceID string, classified ClassifiedError) (*bridgepkg.BridgeInstance, RecoveryDecision, error)
- func (s *Session) SyncInstances(ctx context.Context) ([]subprocess.InitializeBridgeManagedInstance, error)
- type ShutdownHandler
- type SignatureVerifier
- type StateMarker
- type TargetSnapshotHandler
- type TransientError
- type WebhookGuardConfig
- type WebhookHandler
- type WebhookRegistrationHandler
- type WebhookRequest
Constants ¶
const ( // ParentMessageCacheLimit bounds provider-local reply context retained in memory. ParentMessageCacheLimit = 4000 // ParentMessageTextLimit bounds the text copied into one reply-context entry. ParentMessageTextLimit = 500 )
const ( AdapterHandshakePathEnv = "COMPOZY_BRIDGE_ADAPTER_HANDSHAKE_PATH" AdapterOwnershipPathEnv = "COMPOZY_BRIDGE_ADAPTER_OWNERSHIP_PATH" AdapterStatePathEnv = "COMPOZY_BRIDGE_ADAPTER_STATE_PATH" AdapterDeliveryPathEnv = "COMPOZY_BRIDGE_ADAPTER_DELIVERY_PATH" AdapterIngestPathEnv = "COMPOZY_BRIDGE_ADAPTER_INGEST_PATH" AdapterStartsPathEnv = "COMPOZY_BRIDGE_ADAPTER_STARTS_PATH" AdapterShutdownPathEnv = "COMPOZY_BRIDGE_ADAPTER_SHUTDOWN_PATH" AdapterCrashOncePathEnv = "COMPOZY_BRIDGE_ADAPTER_CRASH_ONCE_PATH" )
const HTTPStatusOverloaded = 529
HTTPStatusOverloaded is the non-standard provider overload response status.
Variables ¶
var ErrPeerClosed = errors.New("bridgesdk: peer closed")
ErrPeerClosed is the terminal cause observed by calls made after the peer reaches clean EOF. Serve normalizes that clean shutdown to nil.
var ErrProviderStopped = errors.New("bridgesdk: provider stopped")
ErrProviderStopped reports that a provider stopped while waiting for runtime state.
Functions ¶
func ApplyParentMessage ¶
func ApplyParentMessage(envelope *bridgepkg.InboundMessageEnvelope, message ParentMessage)
ApplyParentMessage merges bounded provider-supplied parent context into an envelope.
func ChunkMessage ¶
ChunkMessage splits text within limit while preserving fenced code blocks. Limits too small for decorations fall back to undecorated lossless chunks.
func CredentialedHTTPClient ¶
CredentialedHTTPClient clones an HTTP client and refuses redirects so provider credentials and mutation bodies never cross an unverified hop.
func DecodeSingleJSONValue ¶
DecodeSingleJSONValue decodes exactly one JSON value and rejects trailing values or tokens.
func DrainAndCloseHTTPResponseBody ¶
func DrainAndCloseHTTPResponseBody(body io.ReadCloser) error
DrainAndCloseHTTPResponseBody drains and closes a provider response, joining both failures.
func FinalizeHTTPResponseBody ¶
func FinalizeHTTPResponseBody( body io.ReadCloser, operationErr error, commitEvidence HTTPResponseCommitEvidence, reportCleanup func(error), ) error
FinalizeHTTPResponseBody preserves cleanup failures until remote commit evidence exists. Once committed, cleanup is reported without invalidating the operation. A missing reporter keeps the cleanup failure on the returned operation error rather than discarding it.
func InboundBatchKey ¶
func InboundBatchKey(envelope bridgepkg.InboundMessageEnvelope) string
InboundBatchKey derives the stable routing-identity key used for batching.
func IsCommittedMutation ¶
IsCommittedMutation reports whether a remote mutation crossed its commit boundary.
func Main ¶
func Main(providerName string, serve ProviderServeFunc)
Main runs one provider command and exits non-zero after a reported failure.
func MarkCommittedMutation ¶
MarkCommittedMutation preserves an existing committed-mutation marker or wraps an error so retry layers can distinguish it from a pre-commit failure.
func NewWebhookHandler ¶
func NewWebhookHandler(config WebhookGuardConfig, next WebhookHandler) (http.Handler, error)
NewWebhookHandler constructs the shared ingress-hardening handler.
func ProviderIdentityCheckRecord ¶
func ProviderIdentityCheckRecord(err error, secretBindings ...string) bridgepkg.BridgeCheckRecord
ProviderIdentityCheckRecord maps a provider identity outcome to one safe, actionable check without copying provider error text into the public record.
func ReadHTTPResponseBody ¶
ReadHTTPResponseBody returns bytes received before an HTTP response read fails.
func RetryDo ¶
func RetryDo[T any](ctx context.Context, config RetryConfig, fn func(context.Context) (T, error)) (T, error)
RetryDo retries a first-party bridge operation through the shared retry runner.
func RunProviderCommand ¶
func RunProviderCommand( providerName string, args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer, serve ProviderServeFunc, ) error
RunProviderCommand dispatches the shared provider command surface.
func ShouldContinueTextDeliveryAfterProgress ¶
ShouldContinueTextDeliveryAfterProgress reports whether a progress failure is safe to consume before the independently addressed text mutation. A committed progress mutation must never be misreported as the outcome of the text event.
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.
func WebhookCheckRecords ¶
func WebhookCheckRecords( ctx context.Context, instance bridgepkg.BridgeInstance, doer webhookHTTPDoer, ) []bridgepkg.BridgeCheckRecord
WebhookCheckRecords validates the external callback configuration and, only for an enabled instance, proves that its public route accepts an HTTP connection. Authentication and validation responses prove route ownership; redirects and missing routes do not.
Types ¶
type AdapterMarkerPaths ¶
type AdapterMarkerPaths struct {
HandshakePath string
OwnershipPath string
StatePath string
DeliveryPath string
IngestPath string
StartsPath string
ShutdownPath string
CrashOncePath string
}
AdapterMarkerPaths is the shared provider-harness marker destination set.
func AdapterMarkerPathsFromProcess ¶
func AdapterMarkerPathsFromProcess() AdapterMarkerPaths
AdapterMarkerPathsFromProcess reads the provider-harness marker destinations.
type AdapterMarkers ¶
type AdapterMarkers struct {
// contains filtered or unexported fields
}
AdapterMarkers centralizes the optional side-effect files consumed by integration harnesses.
func NewAdapterMarkers ¶
func NewAdapterMarkers(provider string, stderr io.Writer) *AdapterMarkers
NewAdapterMarkers resolves marker destinations from the current process environment.
func (*AdapterMarkers) Error ¶
func (m *AdapterMarkers) Error() error
Error returns any secondary writer failure encountered while reporting marker errors.
func (*AdapterMarkers) RecordCrash ¶
func (m *AdapterMarkers) RecordCrash(value any)
RecordCrash writes the one-shot crash marker payload.
func (*AdapterMarkers) RecordDelivery ¶
func (m *AdapterMarkers) RecordDelivery(marker DeliveryMarker)
RecordDelivery appends one provider delivery observation.
func (*AdapterMarkers) RecordIngest ¶
func (m *AdapterMarkers) RecordIngest(marker IngestMarker)
RecordIngest appends one provider inbound observation.
func (*AdapterMarkers) RecordInitialize ¶
func (m *AdapterMarkers) RecordInitialize(marker *InitializeMarker)
RecordInitialize records one provider initialize handshake.
func (*AdapterMarkers) RecordListen ¶
func (m *AdapterMarkers) RecordListen(address string)
RecordListen records the bound webhook address used by integration harnesses.
func (*AdapterMarkers) RecordOwnership ¶
func (m *AdapterMarkers) RecordOwnership(marker OwnershipMarker)
RecordOwnership records provider-owned instance list/get observations.
func (*AdapterMarkers) RecordShutdown ¶
func (m *AdapterMarkers) RecordShutdown(pid int)
RecordShutdown records one provider process shutdown.
func (*AdapterMarkers) RecordStart ¶
func (m *AdapterMarkers) RecordStart(pid int)
RecordStart records one provider process start.
func (*AdapterMarkers) RecordState ¶
func (m *AdapterMarkers) RecordState(marker StateMarker)
RecordState appends one provider-owned state observation.
func (*AdapterMarkers) ReportError ¶
func (m *AdapterMarkers) ReportError(action string, err error)
ReportError preserves provider side-effect diagnostics on the shared stderr writer.
func (*AdapterMarkers) ShouldCrashOnce ¶
func (m *AdapterMarkers) ShouldCrashOnce() bool
ShouldCrashOnce reports whether the integration harness requested one process crash.
type AuthError ¶
type AuthError struct {
Err error
}
AuthError marks an authentication failure explicitly.
type CheckHandler ¶
type CheckHandler func( context.Context, *Session, bridgepkg.BridgeCheckRequest, ) (bridgepkg.BridgeCheckResponse, error)
CheckHandler runs one read-only provider-owned bridge check operation.
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 CommittedMutationError ¶
type CommittedMutationError struct {
Err error
}
CommittedMutationError marks a remote mutation that the provider accepted, but whose required result could not be materialized locally. Retrying such an operation could duplicate the remote side effect.
func (*CommittedMutationError) Error ¶
func (e *CommittedMutationError) Error() string
func (*CommittedMutationError) Unwrap ¶
func (e *CommittedMutationError) Unwrap() error
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 DeliveryChunkCursor ¶
type DeliveryChunkCursor struct {
// contains filtered or unexported fields
}
DeliveryChunkCursor records the successfully materialized prefix of one provider delivery attempt. Providers retain it when an explicit later-chunk failure is returned so the daemon's resume request starts at the first unsent chunk instead of duplicating the prefix.
func BeginDeliveryChunks ¶
func BeginDeliveryChunks( current DeliveryChunkCursor, eventSeq int64, mode DeliveryChunkMode, chunkCount int, content string, lastRemoteMessageID string, replaceRemoteMessageID string, ) DeliveryChunkCursor
BeginDeliveryChunks reuses a matching partial cursor or starts a fresh cursor for a different event, delivery mode, content, or chunk layout.
func (DeliveryChunkCursor) Active ¶
func (c DeliveryChunkCursor) Active() bool
Active reports whether the cursor owns an in-progress chunk sequence.
func (DeliveryChunkCursor) Advance ¶
func (c DeliveryChunkCursor) Advance(remoteMessageID string) DeliveryChunkCursor
Advance records one successfully materialized chunk.
func (DeliveryChunkCursor) LastRemoteMessageID ¶
func (c DeliveryChunkCursor) LastRemoteMessageID() string
LastRemoteMessageID returns the last remote handle materialized so far.
func (DeliveryChunkCursor) NextChunk ¶
func (c DeliveryChunkCursor) NextChunk() int
NextChunk returns the first chunk index that has not been acknowledged by the provider API.
func (DeliveryChunkCursor) ReplaceRemoteMessageID ¶
func (c DeliveryChunkCursor) ReplaceRemoteMessageID() string
ReplaceRemoteMessageID returns the original remote handle replaced by this chunk sequence, when the delivery began as an update.
type DeliveryChunkMode ¶
type DeliveryChunkMode string
DeliveryChunkMode distinguishes a multi-chunk create from an update that reuses an existing remote message as its first chunk.
const ( DeliveryChunkModeCreate DeliveryChunkMode = "create" DeliveryChunkModeUpdate DeliveryChunkMode = "update" )
type DeliveryHandler ¶
type DeliveryHandler func(context.Context, *Session, bridgepkg.DeliveryRequest) (bridgepkg.DeliveryAck, error)
DeliveryHandler handles one daemon-originated `bridges/deliver` request.
type DeliveryMarker ¶
type DeliveryMarker struct {
PID int `json:"pid"`
Request bridgepkg.DeliveryRequest `json:"request"`
Ack *bridgepkg.DeliveryAck `json:"ack,omitempty"`
Error string `json:"error,omitempty"`
}
DeliveryMarker records one provider delivery request and acknowledgement.
type DeliveryStateStore ¶
type DeliveryStateStore[S any] struct { // contains filtered or unexported fields }
DeliveryStateStore owns provider-specific delivery snapshots without deciding their lifecycle.
func NewDeliveryStateStore ¶
func NewDeliveryStateStore[S any](options ...DeliveryStateStoreOption[S]) *DeliveryStateStore[S]
NewDeliveryStateStore creates an empty typed delivery-state store.
func (*DeliveryStateStore[S]) Delete ¶
func (s *DeliveryStateStore[S]) Delete(deliveryID string) (S, bool)
Delete removes and returns one delivery state.
func (*DeliveryStateStore[S]) Drain ¶
func (s *DeliveryStateStore[S]) Drain() map[string]S
Drain removes and returns every delivery state.
func (*DeliveryStateStore[S]) Load ¶
func (s *DeliveryStateStore[S]) Load(deliveryID string) (S, bool)
Load returns one delivery state.
func (*DeliveryStateStore[S]) Store ¶
func (s *DeliveryStateStore[S]) Store(deliveryID string, state S)
Store replaces one delivery state.
func (*DeliveryStateStore[S]) TransformAll ¶
func (s *DeliveryStateStore[S]) TransformAll(transform func(string, S) S) map[string]S
TransformAll atomically replaces every retained state and returns the prior snapshot.
func (*DeliveryStateStore[S]) Update ¶
func (s *DeliveryStateStore[S]) Update(deliveryID string, update func(S) S) bool
Update mutates one delivery state atomically and reports whether it existed.
func (*DeliveryStateStore[S]) UpdateOrCreate ¶
func (s *DeliveryStateStore[S]) UpdateOrCreate( deliveryID string, resolve func(S, bool) S, ) (S, bool)
UpdateOrCreate atomically resolves one delivery state and reports whether it already existed.
type DeliveryStateStoreOption ¶
type DeliveryStateStoreOption[S any] func(*DeliveryStateStore[S])
DeliveryStateStoreOption configures bounded provider delivery-state retention.
func WithDeliveryStateRetention ¶
func WithDeliveryStateRetention[S any]( maxEntries int, ttl time.Duration, now func() time.Time, ) DeliveryStateStoreOption[S]
WithDeliveryStateRetention bounds retained state by least-recent use and age.
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" ErrorClassOverloaded ErrorClass = "overloaded" ErrorClassServerError ErrorClass = "server_error" 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 HTTPResponseCommitEvidence ¶
type HTTPResponseCommitEvidence uint8
HTTPResponseCommitEvidence records why retrying a successful HTTP operation is unsafe.
const ( // HTTPResponseCommitUnconfirmed means no remote mutation has been proven. HTTPResponseCommitUnconfirmed HTTPResponseCommitEvidence = iota // HTTPResponseCommittedBySuccessStatus means a successful status confirms the mutation. HTTPResponseCommittedBySuccessStatus )
type HTTPResponseCommitPolicy ¶
type HTTPResponseCommitPolicy uint8
HTTPResponseCommitPolicy defines which observation proves an HTTP operation committed remotely.
const ( // HTTPResponseNoCommit keeps response cleanup failures on the returned operation error. HTTPResponseNoCommit HTTPResponseCommitPolicy = iota // HTTPResponseCommitOnSuccessStatus treats a successful status as remote commit evidence. HTTPResponseCommitOnSuccessStatus )
func (HTTPResponseCommitPolicy) Evidence ¶
func (p HTTPResponseCommitPolicy) Evidence() HTTPResponseCommitEvidence
Evidence derives observed commit evidence after a successful status.
type HealthHandler ¶
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) GetBridgeInstance ¶
func (c *HostAPIClient) GetBridgeInstance( ctx context.Context, bridgeInstanceID string, ) (*bridgepkg.BridgeInstance, error)
GetBridgeInstance returns one provider-owned bridge instance.
func (*HostAPIClient) IngestBridgeMessage ¶
func (c *HostAPIClient) IngestBridgeMessage( ctx context.Context, envelope bridgepkg.InboundMessageEnvelope, ) (*bridgepkg.BridgesMessagesIngestResult, error)
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 ¶
func (c *HostAPIClient) ReportBridgeInstanceState( ctx context.Context, params bridgepkg.BridgesInstancesReportStateParams, ) (*bridgepkg.BridgeInstance, error)
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 ¶
func (b *InboundBatcher) Enqueue(envelope bridgepkg.InboundMessageEnvelope) error
Enqueue appends one inbound envelope to the routing-identity batch.
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 IngestMarker ¶
type IngestMarker struct {
Envelope bridgepkg.InboundMessageEnvelope `json:"envelope"`
Result bridgepkg.BridgesMessagesIngestResult `json:"result"`
Error string `json:"error,omitempty"`
}
IngestMarker records one provider inbound envelope and daemon result.
type InitializeHandler ¶
InitializeHandler runs after the provider runtime receives the negotiated initialize request and seeds its Host API client and managed-instance cache.
type InitializeMarker ¶
type InitializeMarker struct {
Request subprocess.InitializeRequest `json:"request"`
Response subprocess.InitializeResponse `json:"response"`
}
InitializeMarker records the negotiated provider handshake for integration tests.
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 a launch-time bound secret only when the instance id is unique across profiles; use BoundSecretValueForProfile for shared ids.
func (*InstanceCache) BoundSecretValueForProfile ¶
func (c *InstanceCache) BoundSecretValueForProfile( profileID string, instanceID string, bindingName string, ) (string, bool)
BoundSecretValueForProfile returns one secret only for the exact profile-owned instance.
func (*InstanceCache) Get ¶
func (c *InstanceCache) Get(id string) (*subprocess.InitializeBridgeManagedInstance, bool)
Get returns one managed instance snapshot by id when that id is unique across profiles; callers with a shared id must use GetForProfile.
func (*InstanceCache) GetForProfile ¶
func (c *InstanceCache) GetForProfile( profileID string, instanceID string, ) (*subprocess.InitializeBridgeManagedInstance, bool)
GetForProfile returns one managed instance owned by the exact profile and id.
func (*InstanceCache) List ¶
func (c *InstanceCache) List() []subprocess.InitializeBridgeManagedInstance
List returns every managed instance snapshot ordered by profile and then instance id.
func (*InstanceCache) Reset ¶
func (c *InstanceCache) Reset(runtime *subprocess.InitializeBridgeRuntime)
Reset replaces the managed-instance snapshot with the provided runtime grant.
func (*InstanceCache) Snapshot ¶
func (c *InstanceCache) Snapshot() *subprocess.InitializeBridgeRuntime
Snapshot returns the current managed-runtime snapshot ordered by profile and then instance id.
func (*InstanceCache) Sync ¶
func (c *InstanceCache) Sync( ctx context.Context, host *HostAPIClient, ) ([]subprocess.InitializeBridgeManagedInstance, error)
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 ManagedConfigPrepare ¶
ManagedConfigPrepare applies provider-specific conflicts, listeners, and initial probes.
type ManagedConfigReconciler ¶
type ManagedConfigReconciler[C any] struct { Routes *RouteTable[C] Resolve ManagedConfigResolver[C] Prepare ManagedConfigPrepare[C] Finalize ManagedConfigPrepare[C] Identity func(C) string Merge RouteMergeFunc[C] OnRemoved func(C) error OnPublish func() }
ManagedConfigReconciler atomically resolves and swaps provider configs.
func (*ManagedConfigReconciler[C]) Publish ¶
func (r *ManagedConfigReconciler[C]) Publish(configs []C) error
Publish atomically replaces the current route snapshot with already-resolved configs.
func (*ManagedConfigReconciler[C]) Reconcile ¶
func (r *ManagedConfigReconciler[C]) Reconcile( ctx context.Context, session *Session, managed []subprocess.InitializeBridgeManagedInstance, ) ([]C, error)
Reconcile replaces the route table with one complete managed-instance snapshot.
type ManagedConfigResolver ¶
type ManagedConfigResolver[C any] func(*Session, subprocess.InitializeBridgeManagedInstance) C
ManagedConfigResolver converts one daemon-managed instance into provider-specific config.
type OwnershipMarker ¶
type OwnershipMarker struct {
Listed []bridgepkg.BridgeInstance `json:"listed,omitempty"`
Fetched []bridgepkg.BridgeInstance `json:"fetched,omitempty"`
Error string `json:"error,omitempty"`
}
OwnershipMarker records provider-owned instance list/get observations.
type ParentMessage ¶
ParentMessage is the bounded reply context retained for one inbound message.
type ParentMessageCache ¶
type ParentMessageCache struct {
// contains filtered or unexported fields
}
ParentMessageCache retains a deterministic least-recently-used reply-context window.
func NewParentMessageCache ¶
func NewParentMessageCache(capacity int) *ParentMessageCache
NewParentMessageCache creates a cache capped at ParentMessageCacheLimit entries.
func (*ParentMessageCache) Delete ¶
func (c *ParentMessageCache) Delete(key ParentMessageKey)
Delete removes one parent message from the cache.
func (*ParentMessageCache) EnrichReply ¶
func (c *ParentMessageCache) EnrichReply( envelope *bridgepkg.InboundMessageEnvelope, parentMessageID string, ) bool
EnrichReply fills reply context from a provider-local cache without network access.
func (*ParentMessageCache) Get ¶
func (c *ParentMessageCache) Get(key ParentMessageKey) (ParentMessage, bool)
Get returns one parent message and promotes it to most recently used.
func (*ParentMessageCache) Put ¶
func (c *ParentMessageCache) Put(key ParentMessageKey, message ParentMessage)
Put records one normalized parent message and promotes it to most recently used.
func (*ParentMessageCache) RememberEnvelope ¶
func (c *ParentMessageCache) RememberEnvelope(envelope bridgepkg.InboundMessageEnvelope)
RememberEnvelope records the reply context exposed by one accepted inbound envelope.
func (*ParentMessageCache) RememberParent ¶
func (c *ParentMessageCache) RememberParent( envelope bridgepkg.InboundMessageEnvelope, parentMessageID string, message ParentMessage, )
RememberParent records provider-supplied parent context after ingress authorization succeeds.
type ParentMessageKey ¶
type ParentMessageKey struct {
WorkspaceID string
BridgeInstanceID string
ConversationID string
MessageID string
}
ParentMessageKey isolates one provider message inside its workspace conversation.
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 ¶
NewPeer constructs a JSON-RPC peer bound to the provided reader and writer. Stdin must implement io.ReadCloser. The peer owns it after construction and closes it to interrupt reads when serving terminates.
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 ProgressAccumulator ¶
type ProgressAccumulator struct {
// contains filtered or unexported fields
}
ProgressAccumulator owns one route's mutable progress bubble state.
func NewProgressAccumulator ¶
func NewProgressAccumulator( cfg ProgressConfig, sink ProgressSink, now func() time.Time, ) *ProgressAccumulator
NewProgressAccumulator constructs state; a zero edit interval defaults to 1.5 seconds.
func (*ProgressAccumulator) Flush ¶
func (a *ProgressAccumulator) Flush(ctx context.Context) error
Flush writes pending accumulated progress immediately.
func (*ProgressAccumulator) OnContent ¶
func (a *ProgressAccumulator) OnContent(ctx context.Context) error
OnContent flushes pending progress, stops typing, and closes the current editable bubble.
func (*ProgressAccumulator) OnProgress ¶
func (a *ProgressAccumulator) OnProgress(ctx context.Context, event bridgepkg.ToolProgress) error
OnProgress records one tool lifecycle line and applies due provider updates.
func (*ProgressAccumulator) PendingFlushDelay ¶
func (a *ProgressAccumulator) PendingFlushDelay() (time.Duration, bool)
PendingFlushDelay reports when a throttled accumulated edit is due.
type ProgressCancel ¶
type ProgressCancel func() bool
ProgressCancel stops one scheduled callback and reports whether it was canceled before running.
type ProgressConfig ¶
type ProgressConfig struct {
bridgepkg.ProgressConfig
Target bridgepkg.DeliveryTarget
MaxMessageLen int // Values through 64 use the conservative 4,000-unit default.
Len func(string) int // Nil uses byte length.
}
ProgressConfig binds settings to one target; empty mode/grouping default to all/accumulate.
type ProgressDispatcher ¶
type ProgressDispatcher struct {
// contains filtered or unexported fields
}
ProgressDispatcher schedules accumulator edits without tying them to a short delivery RPC context.
func NewProgressDispatcher ¶
func NewProgressDispatcher( accumulator *ProgressAccumulator, options ...ProgressDispatcherOption, ) *ProgressDispatcher
NewProgressDispatcher wraps one accumulator with a cancelable throttle scheduler.
func (*ProgressDispatcher) Close ¶
func (d *ProgressDispatcher) Close()
Close cancels pending work and waits for a callback that is already running.
func (*ProgressDispatcher) Flush ¶
func (d *ProgressDispatcher) Flush(ctx context.Context) error
Flush cancels the pending timer and writes accumulated progress immediately.
func (*ProgressDispatcher) LastAsyncError ¶
func (d *ProgressDispatcher) LastAsyncError() error
LastAsyncError returns the most recent scheduled flush failure, if any.
func (*ProgressDispatcher) OnContent ¶
func (d *ProgressDispatcher) OnContent(ctx context.Context) error
OnContent cancels the pending timer, flushes progress, clears typing, and resets the bubble.
func (*ProgressDispatcher) OnProgress ¶
func (d *ProgressDispatcher) OnProgress(ctx context.Context, event bridgepkg.ToolProgress) error
OnProgress records one event and schedules any edit held inside the throttle window.
type ProgressDispatcherOption ¶
type ProgressDispatcherOption func(*progressDispatcherOptions)
ProgressDispatcherOption customizes scheduled progress delivery.
func WithProgressAsyncErrorHandler ¶
func WithProgressAsyncErrorHandler(handler func(error)) ProgressDispatcherOption
WithProgressAsyncErrorHandler observes scheduled flush failures after they are retained locally.
func WithProgressAsyncTimeout ¶
func WithProgressAsyncTimeout(timeout time.Duration) ProgressDispatcherOption
WithProgressAsyncTimeout bounds detached scheduled provider calls.
func WithProgressSchedule ¶
func WithProgressSchedule(schedule ProgressSchedule) ProgressDispatcherOption
WithProgressSchedule replaces the real timer scheduler, primarily for deterministic tests.
type ProgressHandler ¶
type ProgressHandler func(context.Context, *Session, bridgepkg.DeliveryRequest) (bridgepkg.DeliveryAck, error)
ProgressHandler handles presentation-only tool progress and the empty final that closes a progress-only turn. When omitted, the runtime acknowledges both without invoking the provider's text handler.
type ProgressSchedule ¶
type ProgressSchedule func(delay time.Duration, callback func()) ProgressCancel
ProgressSchedule schedules one callback after a delay and returns its cancellation function.
type ProgressSink ¶
type ProgressSink interface {
Post(ctx context.Context, target bridgepkg.DeliveryTarget, text string) (remoteID string, err error)
Edit(ctx context.Context, target bridgepkg.DeliveryTarget, remoteID string, text string) error
Typing(ctx context.Context, target bridgepkg.DeliveryTarget, active bool) error
React(ctx context.Context, target bridgepkg.DeliveryTarget, reaction string) error
}
ProgressSink applies provider-specific progress messages and affordances.
type ProviderHTTPConfig ¶
type ProviderHTTPConfig struct {
ReadHeaderTimeout time.Duration
IdleTimeout time.Duration
Handler http.Handler
RoutesReady <-chan struct{}
Go func(func()) bool
OnError func(error)
}
ProviderHTTPConfig configures one shared provider webhook server.
type ProviderHTTPServer ¶
type ProviderHTTPServer struct {
// contains filtered or unexported fields
}
ProviderHTTPServer owns one provider listener/server lifecycle.
func NewProviderHTTPServer ¶
func NewProviderHTTPServer(config ProviderHTTPConfig) (*ProviderHTTPServer, error)
NewProviderHTTPServer creates one provider webhook server owner.
func (*ProviderHTTPServer) Address ¶
func (s *ProviderHTTPServer) Address() string
Address returns the configured listen address while the server is active.
func (*ProviderHTTPServer) Shutdown ¶
func (s *ProviderHTTPServer) Shutdown(ctx context.Context) error
Shutdown detaches and closes the provider listener/server.
func (*ProviderHTTPServer) Start ¶
func (s *ProviderHTTPServer) Start(listenAddr string) error
Start listens once at the requested address and serves the provider handler.
type ProviderHost ¶
type ProviderHost struct {
// contains filtered or unexported fields
}
ProviderHost centralizes retried ownership, state-report, and ingest Host API calls.
func NewProviderHost ¶
func NewProviderHost(
stop <-chan struct{},
markers *AdapterMarkers,
opts ...ProviderHostOption,
) *ProviderHost
NewProviderHost creates shared Host API operations for one provider lifecycle.
func (*ProviderHost) ForgetStatus ¶
func (h *ProviderHost) ForgetStatus(bridgeInstanceID string)
ForgetStatus removes retained state for an instance no longer owned by the provider.
func (*ProviderHost) GetOwnedInstance ¶
func (h *ProviderHost) GetOwnedInstance( ctx context.Context, session ProviderHostSession, bridgeInstanceID string, ) (*bridgepkg.BridgeInstance, error)
GetOwnedInstance reads one provider-owned bridge instance with startup retry.
func (*ProviderHost) IngestBridgeMessage ¶
func (h *ProviderHost) IngestBridgeMessage( ctx context.Context, session ProviderHostSession, envelope bridgepkg.InboundMessageEnvelope, ) (*bridgepkg.BridgesMessagesIngestResult, error)
IngestBridgeMessage submits one normalized inbound envelope and records its harness marker.
func (*ProviderHost) ReportReadyIfNeeded ¶
func (h *ProviderHost) ReportReadyIfNeeded( ctx context.Context, session ProviderHostSession, bridgeInstanceID string, ) error
ReportReadyIfNeeded restores ready state only when the provider previously reported another state.
func (*ProviderHost) ReportState ¶
func (h *ProviderHost) ReportState( ctx context.Context, session ProviderHostSession, bridgeInstanceID string, status bridgepkg.BridgeStatus, degradation *bridgepkg.BridgeDegradation, ) error
ReportState writes one provider-owned bridge status and marker.
func (*ProviderHost) Retry ¶
Retry retries only the startup NotInitialized RPC error with bounded backoff.
func (*ProviderHost) Statuses ¶
func (h *ProviderHost) Statuses() map[string]bridgepkg.BridgeStatus
Statuses returns the last provider-reported status for every managed instance.
func (*ProviderHost) SyncOwnedInstances ¶
func (h *ProviderHost) SyncOwnedInstances( ctx context.Context, session ProviderHostSession, ) ([]subprocess.InitializeBridgeManagedInstance, error)
SyncOwnedInstances refreshes one provider's managed-instance cache with startup retry.
type ProviderHostOption ¶
type ProviderHostOption func(*ProviderHost)
ProviderHostOption customizes shared provider Host API behavior.
func WithProviderHostRetryWait ¶
func WithProviderHostRetryWait(wait providerHostRetryWait) ProviderHostOption
WithProviderHostRetryWait replaces retry waiting for deterministic tests.
type ProviderHostSession ¶
type ProviderHostSession interface {
SyncInstances(context.Context) ([]subprocess.InitializeBridgeManagedInstance, error)
CachedInstances() []subprocess.InitializeBridgeManagedInstance
GetBridgeInstance(context.Context, string) (*bridgepkg.BridgeInstance, error)
ReportBridgeInstanceState(
context.Context,
bridgepkg.BridgesInstancesReportStateParams,
) (*bridgepkg.BridgeInstance, error)
IngestBridgeMessage(
context.Context,
bridgepkg.InboundMessageEnvelope,
) (*bridgepkg.BridgesMessagesIngestResult, error)
}
ProviderHostSession is the narrow Host API surface used by shared provider lifecycle code.
type ProviderInitialState ¶
type ProviderInitialState struct {
BridgeInstanceID string
Status bridgepkg.BridgeStatus
Degradation *bridgepkg.BridgeDegradation
}
ProviderInitialState is one resolved instance state emitted after reconciliation.
type ProviderLifecycle ¶
type ProviderLifecycle struct {
// contains filtered or unexported fields
}
ProviderLifecycle owns provider session, initialization work, stop state, and health error.
func NewProviderLifecycle ¶
func NewProviderLifecycle(config ProviderLifecycleConfig) (*ProviderLifecycle, error)
NewProviderLifecycle creates one shared provider lifecycle.
func (*ProviderLifecycle) ClearError ¶
func (l *ProviderLifecycle) ClearError()
ClearError clears the provider health error.
func (*ProviderLifecycle) Context ¶
func (l *ProviderLifecycle) Context() context.Context
Context returns a lifecycle-owned context canceled when provider shutdown begins.
func (*ProviderLifecycle) Go ¶
func (l *ProviderLifecycle) Go(run func()) bool
Go starts one lifecycle-owned goroutine unless shutdown already began. Panics in provider callbacks are recovered and exposed through Health.
func (*ProviderLifecycle) Health ¶
func (l *ProviderLifecycle) Health() error
Health returns provider-specific health or the shared lifecycle error.
func (*ProviderLifecycle) Host ¶
func (l *ProviderLifecycle) Host() *ProviderHost
Host returns the shared provider Host API operations.
func (*ProviderLifecycle) Initialize ¶
func (l *ProviderLifecycle) Initialize(ctx context.Context, session *Session) error
Initialize stores the negotiated session and starts ownership reconciliation.
func (*ProviderLifecycle) Initialized ¶
func (l *ProviderLifecycle) Initialized() <-chan struct{}
Initialized closes after ownership, reconciliation, and initial state reporting finish.
func (*ProviderLifecycle) MarkRoutesReady ¶
func (l *ProviderLifecycle) MarkRoutesReady()
MarkRoutesReady admits delivery after the provider atomically publishes its first route snapshot.
func (*ProviderLifecycle) RoutesReady ¶
func (l *ProviderLifecycle) RoutesReady() <-chan struct{}
RoutesReady closes when the provider publishes or definitively rejects its first route snapshot.
func (*ProviderLifecycle) Serve ¶
func (l *ProviderLifecycle) Serve( ctx context.Context, runtime *Runtime, stdin io.Reader, stdout io.Writer, ) error
Serve records process startup and runs the shared RPC runtime.
func (*ProviderLifecycle) Session ¶
func (l *ProviderLifecycle) Session() *Session
Session returns the negotiated provider session.
func (*ProviderLifecycle) SetError ¶
func (l *ProviderLifecycle) SetError(err error)
SetError records one provider health error.
func (*ProviderLifecycle) Shutdown ¶
func (l *ProviderLifecycle) Shutdown( ctx context.Context, _ *Session, request subprocess.ShutdownRequest, ) error
Shutdown stops provider resources, joins lifecycle work, and records shutdown.
func (*ProviderLifecycle) Stop ¶
func (l *ProviderLifecycle) Stop()
Stop closes the provider stop signal and provider-specific resources once.
func (*ProviderLifecycle) StopChannel ¶
func (l *ProviderLifecycle) StopChannel() <-chan struct{}
StopChannel returns the provider lifecycle stop signal.
func (*ProviderLifecycle) Stopped ¶
func (l *ProviderLifecycle) Stopped() bool
Stopped reports whether provider shutdown began.
type ProviderLifecycleConfig ¶
type ProviderLifecycleConfig struct {
ProviderName string
Markers *AdapterMarkers
Host *ProviderHost
Reconcile ProviderReconcileFunc
FinalizeInitialize func(error)
OnStop func()
ShutdownResources func(context.Context) error
HealthCheck func() error
InitializeTimeout time.Duration
ShutdownTimeout time.Duration
}
ProviderLifecycleConfig configures shared provider lifecycle orchestration.
type ProviderReconcileFunc ¶
type ProviderReconcileFunc func( context.Context, []subprocess.InitializeBridgeManagedInstance, ) ([]ProviderInitialState, error)
ProviderReconcileFunc reconciles one complete managed-instance snapshot.
type ProviderServeFunc ¶
ProviderServeFunc starts one provider over the supplied standard streams.
type RPCHandler ¶
RPCHandler handles one inbound JSON-RPC request.
type RateLimitError ¶
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 RetryAttempt ¶
type RetryAttempt struct {
Number int
MaxAttempts int
Delay time.Duration
Classified ClassifiedError
}
RetryAttempt describes one bridge operation failure that will be retried.
type RetryBackoff ¶
RetryBackoff bounds one provider failure class's delay sequence.
type RetryConfig ¶
type RetryConfig struct {
Attempts int
StandardBackoff RetryBackoff
OverloadedBackoff RetryBackoff
RandFloat func() float64
Sleep func(context.Context, time.Duration) error
OnRetry func(context.Context, RetryAttempt) error
}
RetryConfig configures bridge-provider retry classification and backoff.
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns the bridge-sdk default retry policy.
type RouteMergeFunc ¶
type RouteMergeFunc[C any] func(previous C, next C) C
RouteMergeFunc carries provider-owned resources from an existing config into its replacement. It must be deterministic and safe to invoke again when reconciliation publishes a finalized snapshot.
type RoutePathFunc ¶
RoutePathFunc returns every normalized webhook path owned by one resolved config.
type RouteTable ¶
type RouteTable[C any] struct { // contains filtered or unexported fields }
RouteTable stores resolved configs by instance and indexes zero or more configs per path.
func NewRouteTable ¶
func NewRouteTable[C any](pathKeys RoutePathFunc[C]) *RouteTable[C]
NewRouteTable creates an empty typed route table.
func (*RouteTable[C]) ByPath ¶
func (t *RouteTable[C]) ByPath(path string) []C
ByPath returns every config indexed under one normalized webhook path.
func (*RouteTable[C]) Get ¶
func (t *RouteTable[C]) Get(instanceID string) (C, bool)
Get returns one config by bridge instance id.
func (*RouteTable[C]) Replace ¶
func (t *RouteTable[C]) Replace(next map[string]C, merge RouteMergeFunc[C]) []C
Replace atomically swaps all configs and returns values removed from the table.
func (*RouteTable[C]) ReplaceWithCleanup ¶
func (t *RouteTable[C]) ReplaceWithCleanup( next map[string]C, merge RouteMergeFunc[C], cleanup func(C) error, ) error
ReplaceWithCleanup commits a route swap only after every removed config is cleaned successfully.
func (*RouteTable[C]) Snapshot ¶
func (t *RouteTable[C]) Snapshot() map[string]C
Snapshot returns a copy of the current instance map.
func (*RouteTable[C]) Update ¶
func (t *RouteTable[C]) Update(instanceID string, update func(C) C) bool
Update replaces one existing config through a provider-owned mutation.
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.
type RuntimeConfig ¶
type RuntimeConfig struct {
ExtensionInfo subprocess.InitializeExtensionInfo
Initialize InitializeHandler
Deliver DeliveryHandler
Progress ProgressHandler
TargetSnapshots TargetSnapshotHandler
Check CheckHandler
RegisterWebhook WebhookRegistrationHandler
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) AckCommittedResultUnavailable ¶
func (s *Session) AckCommittedResultUnavailable( req bridgepkg.DeliveryRequest, reason string, ) (bridgepkg.DeliveryAck, error)
AckCommittedResultUnavailable acknowledges that a remote mutation committed but its required result cannot be safely resumed or retried.
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) CachedInstances ¶
func (s *Session) CachedInstances() []subprocess.InitializeBridgeManagedInstance
CachedInstances returns the current provider-owned instance snapshot without a Host API call.
func (*Session) GetBridgeInstance ¶
func (s *Session) GetBridgeInstance( ctx context.Context, bridgeInstanceID string, ) (*bridgepkg.BridgeInstance, error)
GetBridgeInstance reads one provider-owned bridge instance through the Host API.
func (*Session) HostAPI ¶
func (s *Session) HostAPI() *HostAPIClient
HostAPI returns the typed bridge Host API client.
func (*Session) IngestBridgeMessage ¶
func (s *Session) IngestBridgeMessage( ctx context.Context, envelope bridgepkg.InboundMessageEnvelope, ) (*bridgepkg.BridgesMessagesIngestResult, error)
IngestBridgeMessage submits one normalized provider envelope through the Host API.
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) ReportBridgeInstanceState ¶
func (s *Session) ReportBridgeInstanceState( ctx context.Context, params bridgepkg.BridgesInstancesReportStateParams, ) (*bridgepkg.BridgeInstance, error)
ReportBridgeInstanceState reports one provider-owned bridge state through the Host API.
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 ¶
func (s *Session) SyncInstances(ctx context.Context) ([]subprocess.InitializeBridgeManagedInstance, error)
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 ¶
SignatureVerifier validates the raw webhook request body before provider mapping runs.
type StateMarker ¶
type StateMarker struct {
BridgeInstanceID string `json:"bridge_instance_id,omitempty"`
Status bridgepkg.BridgeStatus `json:"status"`
Instance bridgepkg.BridgeInstance `json:"instance"`
Error string `json:"error,omitempty"`
}
StateMarker records one provider-owned bridge state report.
type TargetSnapshotHandler ¶
type TargetSnapshotHandler func( context.Context, *Session, bridgepkg.BridgeTargetSnapshotRequest, ) ([]bridgepkg.BridgeTargetSnapshot, error)
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 WebhookRegistrationHandler ¶
type WebhookRegistrationHandler func( context.Context, *Session, bridgepkg.BridgeWebhookRegistrationRequest, ) (bridgepkg.BridgeWebhookRegistrationResponse, error)
WebhookRegistrationHandler registers the configured provider webhook.
type WebhookRequest ¶
WebhookRequest is the provider-facing request payload after ingress guards complete.
Source Files
¶
- batching.go
- cache.go
- chunk.go
- control_checks.go
- dedup.go
- delivery_chunk_cursor.go
- doc.go
- errors.go
- hostapi.go
- http_client.go
- parent_message_cache.go
- peer.go
- peer_handler.go
- peer_terminal.go
- progress.go
- progress_dispatcher.go
- progress_limit.go
- progress_text_state.go
- provider_command.go
- provider_delivery_state.go
- provider_host.go
- provider_http.go
- provider_lifecycle.go
- provider_markers.go
- provider_reconcile.go
- provider_routes.go
- provider_session.go
- response_body.go
- retry.go
- runtime.go
- runtime_control.go
- runtime_delivery.go
- runtime_delivery_ack.go
- runtime_lifecycle.go
- runtime_params.go
- runtime_service.go
- target_snapshots.go
- webhook.go
- webhook_check.go
- webhook_http.go