Documentation
¶
Overview ¶
File core.go implements socket-free client and host protocol state machines.
File frame_receipt.go carries local receive timing atomically with each frame.
Reliable-session validation and bounded in-memory control state.
OPTIONAL capability syntra.reliable-session/1, post-ACTIVE generic-RPC control, no envelope changes, reserved values preserved, app payloads opaque (equality only), no exactly-once claims, no custom crypto (crypto/rand lookup handles only). Network connections use Syntra encryption.
File request_budget.go retains request timing from complete-frame receipt.
Session machines for Syntra v1 Go servers: transport-agnostic Client (initiator) and Host (responder) built on the validation and codec primitives in syntra.go.
A Transport carries exactly one serialized Frame per Send/Recv call in each direction. Hosts supply transports obeying this complete-frame contract. LoopbackPair provides an in-memory Transport for tests and embedding.
Both Client and Host delegate handshake, correlation, and timers to the core.
Context deadlines and cancellation: every blocking call honors ctx. Call derives the wire timeout_ms budget as the minimum of the requested budget and the time remaining on ctx; ctx cancellation sends a best-effort cancel frame and reports CANCELLED (context.Canceled) or DEADLINE_EXCEEDED (context.DeadlineExceeded / budget expiry) without waiting for the late terminal result, which the pump still consumes to keep correlation exact.
Package syntra implements the transport-independent Syntra protocol core, codec, handshake, and sessions in Go. Identity policy, credential storage, application payload schemas, and transport connectivity belong to the host.
File terminal_receipt.go implements opt-in, request-owned terminal retirement.
Index ¶
- Constants
- Variables
- func AllowAllAuthorize(ctx context.Context, principal string, method string) error
- func CheckDuplicateContent(expectedMethod string, expectedPayload []byte, actualMethod string, ...) error
- func CheckEpochAdvance(current, proposed uint64) error
- func CompleteTerminalReceipt(ctx context.Context, operation string, expectedRevision uint64) error
- func DecodeRecovery(data []byte, m proto.Message) error
- func DenyAllAuthorize(ctx context.Context, principal string, method string) error
- func EncodeRecovery(m proto.Message) ([]byte, error)
- func ErrorCodeName(c ErrorCode) string
- func IsAborted(c ErrorCode) bool
- func IsAlreadyExists(c ErrorCode) bool
- func IsAuthFailure(c ErrorCode) bool
- func IsCancelled(c ErrorCode) bool
- func IsClientError(c ErrorCode) bool
- func IsDataLoss(c ErrorCode) bool
- func IsDeadlineExceeded(c ErrorCode) bool
- func IsFailedPrecondition(c ErrorCode) bool
- func IsInternal(c ErrorCode) bool
- func IsInvalidArgument(c ErrorCode) bool
- func IsNotFound(c ErrorCode) bool
- func IsOutOfRange(c ErrorCode) bool
- func IsPermissionDenied(c ErrorCode) bool
- func IsRecoveryMethod(method string) bool
- func IsReservedFieldName(name string) bool
- func IsReservedFieldNumber(n int) bool
- func IsResourceExhausted(c ErrorCode) bool
- func IsRetryable(c ErrorCode) bool
- func IsServerError(c ErrorCode) bool
- func IsUnauthenticated(c ErrorCode) bool
- func IsUnavailable(c ErrorCode) bool
- func IsUnimplemented(c ErrorCode) bool
- func IsUnknown(c ErrorCode) bool
- func IsValidFailure(c ErrorCode) bool
- func MarshalFrame(f *Frame) ([]byte, error)
- func NegotiateVersion(min, max uint32) (uint32, error)
- func NegotiateVersionRanges(clientMin, clientMax, serverMin, serverMax uint32) (uint32, error)
- func NewConnectionID() (string, error)
- func NextEpoch(current uint64) (uint64, error)
- func ValidateBodyCardinality(f *Frame) error
- func ValidateCredentialSize(credential []byte) error
- func ValidateEpoch(epoch uint64) error
- func ValidateFrame(f *Frame) error
- func ValidateFrameForState(f *Frame, st ConnectionState) error
- func ValidateFrameSize(n int) error
- func ValidateHello(h *ClientHello) error
- func ValidateMethod(method string) error
- func ValidatePayloadSize(n int) error
- func ValidateReady(r *ServerReady) error
- func ValidateRecovery(m proto.Message) error
- func ValidateRequestID(f *Frame) error
- func ValidateResult(r *RpcResult) error
- func ValidateResumeCredential(cred []byte) ([]byte, error)
- func ValidateVersion(v uint32) error
- func WithRecoveryHostSession(ctx context.Context, session *RecoveryHostSession) context.Context
- type AuthorizeFunc
- type BodyKind
- type Cancel
- type ChannelIdentity
- type ChannelIdentityProvider
- type ChannelPolicy
- type Checkpoint
- type CheckpointReconciler
- type Client
- func (c *Client) Call(ctx context.Context, method string, payload []byte, timeoutMs uint32) ([]byte, error)
- func (c *Client) Close() error
- func (c *Client) DroppedBytes() uint64
- func (c *Client) DroppedNotifications() uint64
- func (c *Client) IsClosed() bool
- func (c *Client) LossTotals() (dropped uint64, droppedBytes uint64)
- func (c *Client) Notifications() <-chan *Notification
- func (c *Client) Run(ctx context.Context, t Transport) (runErr error)
- func (c *Client) TerminalError() error
- func (c *Client) WaitLossChange(ctx context.Context, lastDropped, lastBytes uint64) (uint64, uint64, error)
- func (c *Client) WaitReady(ctx context.Context) error
- type ClientConfig
- type ClientHello
- type CommitUnknown
- type CommittedPosition
- type ConfirmedLease
- type Connection
- func (c *Connection) AuthFailure() error
- func (c *Connection) AuthSuccess(principal string) error
- func (c *Connection) BeginAuth() error
- func (c *Connection) Close() error
- func (c *Connection) MarkClosed() error
- func (c *Connection) OnHello(h *ClientHello) (uint32, error)
- func (c *Connection) Principal() string
- func (c *Connection) State() ConnectionState
- func (c *Connection) Version() uint32
- type ConnectionState
- type ControlBounds
- type CredentialPolicy
- type DeliveryID
- type DuplicateCache
- type DurableRecord
- type DurableStore
- type ErrorCode
- type ExecutionBudget
- type ExpectedPosition
- type Frame
- func NewCancelFrame(version uint32, requestID uint64) *Frame
- func NewHelloFrame(hello *ClientHello, maxVersion uint32) *Frame
- func NewNotificationFrame(version uint32, n *Notification) *Frame
- func NewReadyFrame(version uint32, ready *ServerReady) *Frame
- func NewRequestFrame(version uint32, requestID uint64, req *RpcRequest) *Frame
- func NewResultFrame(version uint32, requestID uint64, res *RpcResult) *Frame
- func UnmarshalFrame(data []byte) (*Frame, error)
- type FrameReceipt
- type FrameReceiptTransport
- type HandlerFunc
- type HandshakeConfig
- type Host
- func (h *Host) Close() error
- func (h *Host) DisconnectPrincipal(principal string) error
- func (h *Host) Done() <-chan struct{}
- func (h *Host) NotifyAll(payload []byte) error
- func (h *Host) NotifyDirected(principal string, payload []byte) error
- func (h *Host) Serve(ctx context.Context, t Transport) (serveErr error)
- func (h *Host) Wait(ctx context.Context) error
- type HostConfig
- type LeaseProposal
- type MemoryRecoveryStore
- type MemoryStore
- type Notification
- type PersistenceError
- type PersistenceScope
- type QueuedSignal
- type ReconcileOutcome
- type ReconcilerConfig
- type RecoveryClient
- func (c *RecoveryClient) CatchUp(ctx context.Context, request *pb.RecoveryCatchUpRequest) (*pb.RecoveryCatchUpAccepted, error)
- func (c *RecoveryClient) Close()
- func (c *RecoveryClient) Confirm(ctx context.Context, request *pb.RecoveryConfirmRequest) (*pb.RecoveryConfirmResponse, error)
- func (c *RecoveryClient) Inbox() *RecoveryInbox
- func (c *RecoveryClient) Negotiate(ctx context.Context, request *pb.RecoveryNegotiateRequest) (*pb.RecoveryNegotiateResponse, error)
- func (c *RecoveryClient) NextEvent(ctx context.Context, handle []byte) (*RecoveryEvent, error)
- func (c *RecoveryClient) Persist(ctx context.Context, handle, state []byte) error
- func (c *RecoveryClient) Progress(ctx context.Context, handle []byte) (RecoveryProgress, error)
- func (c *RecoveryClient) Replay(ctx context.Context, request *pb.RecoveryReplayRequest) (*pb.RecoveryReplayPage, error)
- func (c *RecoveryClient) SnapshotBytes(ctx context.Context, handle []byte) ([]byte, error)
- func (c *RecoveryClient) SnapshotConfirm(ctx context.Context, request *pb.RecoverySnapshotConfirmRequest) (*pb.RecoverySnapshotInstalled, error)
- func (c *RecoveryClient) SnapshotFetch(ctx context.Context, request *pb.RecoverySnapshotFetchRequest) (*pb.RecoverySnapshotChunk, error)
- func (c *RecoveryClient) SnapshotOffer(ctx context.Context, request *pb.RecoverySnapshotOfferRequest) (*pb.RecoverySnapshotDescriptor, error)
- func (c *RecoveryClient) Subscribe(ctx context.Context, request *pb.RecoverySubscribeRequest, stableStream []byte, ...) (*RecoverySubscription, error)
- func (c *RecoveryClient) Unsubscribe(ctx context.Context, request *pb.RecoveryUnsubscribeRequest) (*pb.RecoveryUnsubscribeResponse, error)
- type RecoveryConnection
- type RecoveryEvent
- type RecoveryHook
- type RecoveryHostSession
- func (h *RecoveryHostSession) Close()
- func (h *RecoveryHostSession) Err() error
- func (h *RecoveryHostSession) Handle(ctx context.Context, method string, payload []byte) (result []byte, resultErr error)
- func (h *RecoveryHostSession) Handler(ctx context.Context, req *RpcRequest) (*RpcResult, error)
- func (h *RecoveryHostSession) NextNotification(ctx context.Context) (result []byte, resultErr error)
- func (h *RecoveryHostSession) PopNotification(ctx context.Context) (result []byte, resultErr error)
- func (h *RecoveryHostSession) Publish(ctx context.Context, identity []byte, b RecoveryStoredBatch) (resultErr error)
- func (h *RecoveryHostSession) RevalidateNotification(ctx context.Context, payload []byte) error
- func (h *RecoveryHostSession) Revoked() bool
- type RecoveryInbox
- type RecoveryInboxCounts
- type RecoveryLimits
- type RecoveryPageBudget
- type RecoveryPersistence
- type RecoveryProgress
- type RecoveryProviderPage
- type RecoveryProviderSnapshot
- type RecoveryProviderStream
- type RecoveryService
- type RecoverySource
- type RecoveryStoreLimits
- type RecoveryStoredBatch
- type RecoverySubscribeIntent
- type RecoverySubscription
- type ReliableManager
- func (m *ReliableManager) Attach(now time.Time, sid SessionID, resumeCred []byte, ...) (uint64, ConfirmedLease, string, []byte, error)
- func (m *ReliableManager) CheckIdle(now time.Time, sid SessionID) (bool, error)
- func (m *ReliableManager) CreateSession(now time.Time, principal string, version uint32, p LeaseProposal) (SessionID, uint64, []byte, ConfirmedLease, error)
- func (m *ReliableManager) Detach(sid SessionID, connectionID string)
- func (m *ReliableManager) DrainForShutdown() ([]SessionID, []QueuedSignal, int, error)
- func (m *ReliableManager) DrainSignals(limit int) []QueuedSignal
- func (m *ReliableManager) Forget(sid SessionID, did DeliveryID) (bool, error)
- func (m *ReliableManager) ForgetAt(now time.Time, sid SessionID, did DeliveryID) (bool, error)
- func (m *ReliableManager) NoteDispatch(now time.Time, sid SessionID, epoch uint64, did DeliveryID, method string, ...) error
- func (m *ReliableManager) ReapExpired(now time.Time) (outcomes, tombstones, resumes int, err error)
- func (m *ReliableManager) Reconcile(now time.Time, sid SessionID, did DeliveryID) (ReconcileOutcome, *StoredOutcome, error)
- func (m *ReliableManager) RecordResult(now time.Time, sid SessionID, epoch uint64, did DeliveryID, method string, ...) (ReconcileOutcome, error)
- func (m *ReliableManager) RecordTombstone(now time.Time, sid SessionID, did DeliveryID, code ErrorCode) error
- func (m *ReliableManager) Revoke(now time.Time, cred []byte) (bool, error)
- func (m *ReliableManager) Signal(sid SessionID, sig SessionSignal) error
- func (m *ReliableManager) SweepIdle(now time.Time) ([]SessionID, error)
- func (m *ReliableManager) TombstoneOf(now time.Time, sid SessionID, did DeliveryID) (ErrorCode, bool, error)
- type RequestBudget
- type RequestBudgetFunc
- type RpcError
- type RpcRequest
- type RpcResult
- type ServerReady
- type SessionID
- type SessionSignal
- type StagedSnapshot
- func (s *StagedSnapshot) Boundary() []byte
- func (s *StagedSnapshot) Completion() (*pb.RecoverySnapshotComplete, error)
- func (s *StagedSnapshot) Install() ([]byte, error)
- func (s *StagedSnapshot) StageChunk(chunk *pb.RecoverySnapshotChunk) error
- func (s *StagedSnapshot) StagePage(index int, bytes, boundary []byte) error
- type StoreError
- type StoredOutcome
- type TerminalAuthority
- type TerminalAuthorityState
- type TerminalChannelBinding
- type TerminalClock
- type TerminalMethodPolicy
- type TerminalObservation
- type TerminalPermit
- func (p *TerminalPermit) CheckTime() error
- func (p *TerminalPermit) Fail(err error)
- func (p *TerminalPermit) Frame() []byte
- func (p *TerminalPermit) Handoff() error
- func (p *TerminalPermit) MatchesChannel(binding TerminalChannelBinding) bool
- func (p *TerminalPermit) Observe(ctx context.Context, requireCommit bool) (TerminalAuthorityState, error)
- type TerminalReceiptDriver
- type TerminalReceiptProvider
- type TerminalTransition
- type Tracker
- func (t *Tracker) Cancel(requestID uint64) bool
- func (t *Tracker) Expired(now time.Time) []uint64
- func (t *Tracker) Finish(requestID uint64) error
- func (t *Tracker) FinishResult(requestID uint64, result *RpcResult) error
- func (t *Tracker) IsCancelled(requestID uint64) bool
- func (t *Tracker) Pending() int
- func (t *Tracker) Start(requestID uint64, method string) error
- func (t *Tracker) StartWithBudget(now time.Time, requestID uint64, method string, timeoutMs uint32) error
- type Transport
- type WireRpcError
Constants ¶
const ( RecoveryCapability = "syntra.update-recovery/1" RecoveryProfileVersion uint32 = 1 RecoveryMethodPrefix = "/syntra.v1.UpdateRecovery/" RecoveryNegotiate = RecoveryMethodPrefix + "Negotiate" RecoverySubscribe = RecoveryMethodPrefix + "Subscribe" RecoveryReplay = RecoveryMethodPrefix + "Replay" RecoveryCatchUp = RecoveryMethodPrefix + "CatchUp" RecoveryConfirm = RecoveryMethodPrefix + "Confirm" RecoverySnapshotConfirm = RecoveryMethodPrefix + "SnapshotConfirm" RecoverySnapshotOffer = RecoveryMethodPrefix + "SnapshotOffer" RecoverySnapshotFetch = RecoveryMethodPrefix + "SnapshotFetch" RecoveryUnsubscribe = RecoveryMethodPrefix + "Unsubscribe" RecoveryMaxPayloadBytes = MaxFrameBytes - 128 )
const ( // MaxFrameBytes is the default 1 MiB on-wire bound for one serialized // Frame (SNTR-WIRE-006). Validators enforce it before allocation. MaxFrameBytes = 1 << 20 // MinSupportedVersion is the lowest Syntra version this binding speaks. MinSupportedVersion uint32 = 1 // MaxSupportedVersion is the highest Syntra version this binding speaks. MaxSupportedVersion uint32 = 1 // MaxMethodLength caps a canonical method string before allocation. MaxMethodLength = 512 // MaxPayloadBytes caps a single opaque RPC or notification payload // before the caller retains it. The serialized-envelope bound stays // authoritative; this keeps one payload from consuming the frame budget. MaxPayloadBytes = 1 << 20 // MaxCredentialBytes caps a ClientHello credential before verification. // Credentials are opaque; the bound prevents a peer from forcing a // large allocation in the verifier. MaxCredentialBytes = 8192 // MaxConnectionIDBytes bounds an opaque diagnostic connection identifier. MaxConnectionIDBytes = 128 // MaxDiagnosticBytes bounds public error text, measured in UTF-8 bytes. MaxDiagnosticBytes = 4096 // DefaultConcurrentRPCs is the default outstanding-call capacity. DefaultConcurrentRPCs = 32 // MaxOutstandingRPCs is the supported per-connection capacity ceiling. MaxOutstandingRPCs = 1024 // DefaultQueueCapacity is the default notification and writer capacity. DefaultQueueCapacity = 256 // MaxQueueCapacity is the supported queue capacity ceiling. MaxQueueCapacity = 1024 // MaxConcurrentRPCs is the minimum concurrent-RPC budget every Syntra // host supports (SNTR-RPC-008). Hosts reject excess with // ResourceExhausted while the connection stays usable. MaxConcurrentRPCs = 16 // MaxHostConcurrentRPCs caps per-connection handler concurrency on the // host side. Hosts fan out to many principals and may need headroom // above the client minimum; values above this fail fast as OutOfRange // so one connection cannot reserve an unbounded worker pool. MaxHostConcurrentRPCs = MaxOutstandingRPCs // ConnectionIDBytes is the 128-bit entropy bound into every // ServerReady.connection_id (SNTR-SESS-002). The ID is a diagnostic // handle, never an authenticator or resume token. ConnectionIDBytes = 16 // ReservedFrameFieldNumber16 is the first reserved envelope number // (SNTR-SER-008, envelope.proto `reserved 16, 17`). ReservedFrameFieldNumber16 = 16 // ReservedFrameFieldNumber17 is the second reserved envelope number. ReservedFrameFieldNumber17 = 17 )
const MaxRPCTimeoutMs uint32 = 120_000
MaxRPCTimeoutMs is the default maximum call budget. Sessions clamp larger requests to their configured maximum.
const ReliableSessionCapability = "syntra.reliable-session/1"
ReliableSessionCapability is the optional capability identifier.
Variables ¶
var DefaultRPCTimeout = 30 * time.Second
DefaultRPCTimeout is the bounded host default applied when RpcRequest.TimeoutMs is zero. Callers SHOULD document any deployment value that differs from this library default.
var ErrRecoveryRetentionMiss = errors.New("syntra: recovery retention unavailable")
ErrRecoveryRetentionMiss requests snapshot fallback without changing continuity.
var ReservedFrameFieldNames = []string{"event", "resume", "ack"} //nolint:gochecknoglobals // allowlist is static.
ReservedFrameFieldNames are the reserved envelope oneof names (envelope.proto `reserved "event", "resume", "ack"`). Decoders that surface field names (JSON, debug strings) must reject these.
Functions ¶
func AllowAllAuthorize ¶
AllowAllAuthorize documents an explicit opt-in to the permissive posture (every bound principal may invoke every method). It exists so call sites can state the allow-all choice instead of leaving HostConfig.Authorize nil by accident.
func CheckDuplicateContent ¶
func CheckDuplicateContent(expectedMethod string, expectedPayload []byte, actualMethod string, actualPayload []byte) error
CheckDuplicateContent requires byte-identical (method, payload) on resend.
func CheckEpochAdvance ¶
CheckEpochAdvance enforces monotonic fencing (proposed > current).
func CompleteTerminalReceipt ¶
CompleteTerminalReceipt reserves, fences, conditionally commits, validates, selects and attempts the configured fixed result for this authorized handler. It must be called BEFORE application mutation; only the configured authority's Commit performs the terminal transition. No payload or caller-created permit is accepted. It writes independently of handler return, then closes this connection on every reserved path. Return nil means complete LOCAL write, not client receipt, durable client storage, or joined cleanup. Loss is unknown and must never trigger automatic mutation replay. A surviving Commit remains charged to the original callback until it actually returns.
func DecodeRecovery ¶
DecodeRecovery bounds fields before allocation and ignores well-formed unknown fields. Ordinary protobuf merge and last-value semantics apply inside profile messages.
func DenyAllAuthorize ¶
DenyAllAuthorize implements the fail-closed default: every RPC is denied with generic PermissionDenied. Wrap or replace with a principal-aware policy to allow selected methods.
func ErrorCodeName ¶
ErrorCodeName returns the canonical UPPER_SNAKE_CASE registry name for c. Unknown numbers report as ERROR_CODE_UNKNOWN so logs never print a bare integer for a failure code.
func IsAlreadyExists ¶
IsAlreadyExists reports whether c is AlreadyExists.
func IsAuthFailure ¶
IsAuthFailure reports whether c denies the caller (Unauthenticated or PermissionDenied).
func IsClientError ¶
IsClientError reports whether c is the caller's fault. These never trip breakers or alerts.
func IsDeadlineExceeded ¶
IsDeadlineExceeded reports whether c is DeadlineExceeded.
func IsFailedPrecondition ¶
IsFailedPrecondition reports whether c is FailedPrecondition.
func IsInvalidArgument ¶
IsInvalidArgument reports whether c is InvalidArgument.
func IsOutOfRange ¶
IsOutOfRange reports whether c is OutOfRange.
func IsPermissionDenied ¶
IsPermissionDenied reports whether c is PermissionDenied.
func IsRecoveryMethod ¶
func IsReservedFieldName ¶
IsReservedFieldName reports whether a decoded field name is in the reserved set ("event", "resume", "ack"). JSON/debug decoders call this when the wire format surfaces names instead of numbers.
func IsReservedFieldNumber ¶
IsReservedFieldNumber reports whether a raw envelope field number is in the reserved set (16, 17). Reserved envelope numbers are rejected on both encoding and decoding (SNTR-SER-008).
func IsResourceExhausted ¶
IsResourceExhausted reports whether c is ResourceExhausted.
func IsRetryable ¶
IsRetryable identifies codes for which an application may consider another attempt with backoff. It does not establish idempotency or authorize replay. Unavailable can leave effects unknown; Aborted requires a new application decision. The caller must establish its operation's retry and deduplication contract before issuing another request.
func IsServerError ¶
IsServerError reports whether c is the host's fault. These feed breaker and alerting policy.
func IsUnauthenticated ¶
IsUnauthenticated reports whether c is Unauthenticated.
func IsUnavailable ¶
IsUnavailable reports whether c is Unavailable.
func IsUnimplemented ¶
IsUnimplemented reports whether c is Unimplemented.
func IsValidFailure ¶
IsValidFailure reports whether c is a legal failure outcome: any code except ErrorCodeUnspecified. Unspecified is representable on the wire but must never be emitted as an RpcError code (SNTR-ERR-001/005).
func MarshalFrame ¶
MarshalFrame encodes f to protobuf binary wire bytes. It validates both the frame value and the emitted wire, including retained unknown fields.
func NegotiateVersion ¶
NegotiateVersion selects the highest version in the intersection of the initiator range and the binding range. It fails closed on empty ranges, inverted ranges, and disjoint ranges.
func NegotiateVersionRanges ¶
NegotiateVersionRanges selects the highest version in the overlap of an explicit client range and an explicit server range. All four bounds must be nonzero with min <= max per side; disjoint ranges fail as Unimplemented.
func NewConnectionID ¶
NewConnectionID generates a fresh 128-bit random identifier hex-encoded to 32 lowercase characters for ServerReady.connection_id. It fails closed on RNG failure so a predictable fallback ID can never be emitted.
func ValidateBodyCardinality ¶
ValidateBodyCardinality enforces exactly-one body set on f. An unset body is representable by the generated codec but is never valid on the wire (RFC 0001 B4).
func ValidateCredentialSize ¶
ValidateCredentialSize rejects oversized credentials before any verifier runs. Empty credentials are an authentication attempt subject to host policy, not a parse error.
func ValidateFrame ¶
ValidateFrame runs the full stateless Frame validation: version, exactly-one body, request_id polarity, and per-body nested rules. Reserved numbers/names are a codec pre-scan concern; by the time a Frame value exists the reserved alternatives cannot be represented, so there is nothing to re-check here beyond cardinality. ACTIVE gating is stateful and lives in ValidateFrameForState.
func ValidateFrameForState ¶
func ValidateFrameForState(f *Frame, st ConnectionState) error
ValidateFrameForState validates envelope shape, then phase legality, then body semantics. CLOSING accepts existing results, cancels, and notifications.
func ValidateFrameSize ¶
ValidateFrameSize rejects a wire length above the 1 MiB bound before the caller allocates a decode buffer. Negative lengths are caller bugs and are rejected as InvalidArgument rather than panicking.
func ValidateHello ¶
func ValidateHello(h *ClientHello) error
ValidateHello checks the nested ClientHello: nonzero versions with min <= max (SNTR-HS-020). Credential emptiness is host policy, not a parse error, so it is not checked here; the host's CredentialPolicy decides.
func ValidateMethod ¶
ValidateMethod checks that method is a canonical /package.Service/Method identifier (SNTR-RPC-001): leading slash, exactly two slashes, non-empty segments, printable ASCII excluding spaces and control characters, within MaxMethodLength. It rejects empty values, missing separators, and oversized inputs before any handler lookup runs. Deployments MAY narrow this further (e.g. per-segment character classes); they MUST NOT widen it.
func ValidatePayloadSize ¶
ValidatePayloadSize rejects an opaque payload above the per-RPC bound before the caller retains it.
func ValidateReady ¶
func ValidateReady(r *ServerReady) error
ValidateReady checks the nested ServerReady. ConnectionId must be non-empty opaque text; it is never an authenticator (SNTR-SESS-002).
func ValidateRecovery ¶
ValidateRecovery validates defined fields; unknown protobuf fields confer no authority.
func ValidateRequestID ¶
ValidateRequestID enforces request_id polarity: zero only for hello, ready, and notification; nonzero for request, result, and cancel (SNTR-WIRE-003, SNTR-RPC-002/010). It requires exactly-one body first so the polarity rule has an unambiguous discriminant.
func ValidateResult ¶
ValidateResult checks the nested RpcResult: exactly one outcome must be selected, even for a zero-byte success (SNTR-WIRE-007). The oneof carries presence, so a nil outcome is never success. An error outcome must carry a nonzero code; unknown nonzero codes are accepted here and mapped to ErrorCodeUnknown by the codec normalization (SNTR-ERR-005), so receipt never crashes or reports success for a future code. Emission strictness stays in the constructors (NewRpcError rejects Unspecified; MarshalFrame normalizes before encoding).
func ValidateResumeCredential ¶
ValidateResumeCredential checks opaque handle bounds (16..256, 32-byte v1).
func ValidateVersion ¶
ValidateVersion checks that v is a legal Syntra version: nonzero and within the binding's supported range. Hello carries the proposed maximum and post-hello frames carry the negotiated version; both are checked with this function at their respective stages (negotiation overlap is decided by NegotiateVersion).
func WithRecoveryHostSession ¶
func WithRecoveryHostSession(ctx context.Context, session *RecoveryHostSession) context.Context
WithRecoveryHostSession binds an admitted handler invocation to the session created from that connection's authenticated ACTIVE identity. Never populate this from request payloads or reuse it on another connection.
Types ¶
type AuthorizeFunc ¶
AuthorizeFunc is the host-owned per-method policy, evaluated for every RPC using the connection's bound principal, before handler effects. Implementations must be nonblocking and may re-check expiry/revocation here. A nil Authorize selects DenyAllAuthorize. Only generic Unauthenticated ("syntra: credential not accepted") and PermissionDenied ("syntra: access denied") codes/messages reach the wire, so policy internals never leak (SNTR-ERR-003). Returning Unauthenticated signals an expired/revoked binding: the per-RPC UNAUTHENTICATED error is sent, then Serve closes the connection by default (SNTR-AUTH-008/SNTR-ASEC-006); use PermissionDenied for per-method denials that keep the connection usable (SNTR-AUTH-009).
type BodyKind ¶
type BodyKind string
BodyKind identifies which Frame oneof alternative is set. It is the switch discriminant for request_id polarity and ACTIVE gating.
const ( // BodyKindNone means no body pointer is set (invalid on the wire). BodyKindNone BodyKind = "" // BodyKindHello is the ClientHello alternative (field 10). BodyKindHello BodyKind = "hello" // BodyKindReady is the ServerReady alternative (field 11). BodyKindReady BodyKind = "ready" // BodyKindRequest is the RpcRequest alternative (field 12). BodyKindRequest BodyKind = "request" // BodyKindResult is the RpcResult alternative (field 13). BodyKindResult BodyKind = "result" // BodyKindCancel is the Cancel alternative (field 14). BodyKindCancel BodyKind = "cancel" // BodyKindNotification is the Notification alternative (field 15). BodyKindNotification BodyKind = "notification" )
func BodyKindOf ¶
BodyKindOf returns which oneof alternative is set on f. It returns BodyKindNone when f is nil, when no body is set, or when more than one body is set. The generated getters return non-nil for at most one alternative because proto.Unmarshal collapses duplicates into the last one; the strict duplicate rejection lives in the codec pre-scan before unmarshal.
type ChannelIdentity ¶
type ChannelIdentity struct {
Mode string
Carrier string
Scope string
Handle [8]byte
Epoch uint64
Principal string
}
ChannelIdentity is the authenticated channel binding supplied by a transport. Principal is evidence for ChannelPolicy to verify, not an automatic RPC identity.
type ChannelIdentityProvider ¶
type ChannelIdentityProvider interface {
ChannelIdentity() (ChannelIdentity, bool)
}
ChannelIdentityProvider supplies channel authentication after receiving a client record. The bool is true only when the responder has authenticated at least one client record, providing fresh confirmation of the channel binding.
type ChannelPolicy ¶
ChannelPolicy verifies a freshly confirmed channel identity and the explicit hello credential, returning the nonempty principal to bind to the session. An empty credential does not implicitly select the channel's Principal.
type Checkpoint ¶
type Checkpoint struct {
// Stream is the stable stream identity (persists across reconnects).
Stream string
// Generation is the continuity epoch.
Generation uint64
// Base is the state required before applying the batch.
Base []byte
// Result is the state reached after applying the complete batch.
Result []byte
}
Checkpoint is one independently ordered stream position: the stable stream identity plus its continuity generation and opaque cursors. Cursors are compared by equality only; the reconciler never orders, increments, or parses them.
type CheckpointReconciler ¶
type CheckpointReconciler struct {
// contains filtered or unexported fields
}
CheckpointReconciler discovers missing final updates without requiring another update: on an independently scheduled tick it compares the last observed result against the last confirmed position and reports streams whose observed result differs from committed. The tick is bounded and idle peers converge without any new batch.
func NewCheckpointReconciler ¶
func NewCheckpointReconciler(cfg ReconcilerConfig) *CheckpointReconciler
NewCheckpointReconciler returns a reconciler with the given bounds.
func (*CheckpointReconciler) Forget ¶
func (r *CheckpointReconciler) Forget(stream string)
Forget stops tracking a stream.
func (*CheckpointReconciler) NoteObserved ¶
func (r *CheckpointReconciler) NoteObserved(cp Checkpoint)
NoteObserved records the last observed (validated or completed) checkpoint for the stream, including the final batch of a stream that then goes idle. Base and Result bytes are deep-copied so later caller mutation cannot alias reconciler state.
func (*CheckpointReconciler) Tick ¶
func (r *CheckpointReconciler) Tick(now time.Time, committed func(stream string) (result []byte, generation uint64, ok bool)) []string
Tick reconciles up to MaxStreamsPerTick streams. For each examined stream whose last observed generation or result differs from committed, it returns a needs-recovery entry keyed by stream. Streams already converged (same generation and byte-identical result) return nothing. The tick runs even when no batch arrived since the last tick. At most MaxStreamsPerTick streams are examined and reported in rotated sorted order for determinism with fairness: each tick starts after the cursor for the last examined stream and wraps around, so permanently diverged low-sorted streams cannot starve later streams. Ticks closer than TickInterval are no-ops.
The committed callback runs WITHOUT the reconciler lock held: it may safely call back into NoteObserved/Forget without deadlocking. The observed set is snapshotted under lock first; lastTick advances before callbacks run so concurrent ticks stay gated.
func (*CheckpointReconciler) TryNoteObserved ¶
func (r *CheckpointReconciler) TryNoteObserved(cp Checkpoint) error
TryNoteObserved records an observation or reports a bound without mutation.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an initiator-side Syntra session. The zero value is invalid; construct with OpenClient. A Client is safe for concurrent Call and notification subscription; one Run pump owns the Transport.
func OpenClient ¶
func OpenClient(cfg ClientConfig) (*Client, error)
OpenClient creates an initiator session. It validates the config and opens the core but performs no I/O; call Run to handshake and pump a Transport.
func (*Client) Call ¶
func (c *Client) Call(ctx context.Context, method string, payload []byte, timeoutMs uint32) ([]byte, error)
Call invokes method with payload and waits for exactly one terminal result. timeoutMs zero selects the configured default. The effective budget starts before readiness and queue admission and is the minimum of MaxTimeout, the requested budget and ctx's remaining time. On ctx end the binding sends a best-effort cancel and reports CANCELLED (ctx canceled) or DEADLINE_EXCEEDED (ctx deadline / budget expiry). A successful outcome returns the opaque payload bytes; an error outcome is returned as *RpcError (branch on Code, never on message text).
func (*Client) Close ¶
Close deterministically releases the session: in-flight calls complete with UNAVAILABLE, the notification stream closes, and the core is destroyed exactly once. A second Close reports FailedPrecondition so double-close bugs surface instead of passing. Close also closes the owned Transport, interrupting pending reads and writes.
func (*Client) DroppedBytes ¶
DroppedBytes reports cumulative notification payload bytes discarded under overflow. It pairs with DroppedNotifications: both advance exactly once per drop (no double-counting).
func (*Client) DroppedNotifications ¶
DroppedNotifications reports notifications discarded under overflow.
func (*Client) IsClosed ¶
IsClosed reports the session's admission fence without waiting for teardown.
func (*Client) LossTotals ¶
LossTotals reports cumulative notification-loss totals for the session: (dropped_count, dropped_bytes) summed over the public notifyCh queue and the linked core queue. Bounds are unchanged on both queues; both stay non-blocking and drop the newest notification. The two layers are disjoint (a notification dropped in the core never reaches the public queue), so the sum counts every drop exactly once. Totals are monotonic across Close: the last-known core totals are cached at Close and the max of live and cached is returned.
func (*Client) Notifications ¶
func (c *Client) Notifications() <-chan *Notification
Notifications returns the notification stream. The channel is closed when the session closes. Overflow drops the newest notification and counts it; see DroppedNotifications. Receive promptly or size NotifyBuffer for bursts.
func (*Client) Run ¶
Run handshakes on t, then pumps frames until ctx ends, the transport fails, a fatal protocol violation arrives, or Close is called. It returns nil only on a clean shutdown (Close or ctx end with no outstanding violation); transport and protocol failures are returned. Call Run once per Client in its own goroutine; concurrent Calls share the pump. Run owns t and closes it on every terminal path, including handshake failure. The handshake has a five-second deadline, shortened by ctx; that deadline does not limit the activated connection's lifetime.
func (*Client) TerminalError ¶
TerminalError returns the first run failure as soon as it is observed, even while transport shutdown is still joining. A local Close is clean.
func (*Client) WaitLossChange ¶
func (c *Client) WaitLossChange(ctx context.Context, lastDropped, lastBytes uint64) (uint64, uint64, error)
WaitLossChange blocks until the cumulative loss totals differ from lastDropped/lastBytes, the session closes, or ctx ends. It returns the current totals. Every waiter observes the same carried totals (broadcast wakeup: all concurrent waiters fire, not just one); a waiter subscribed after the drop reads them as current state instead of missing the signal. A closed session returns current totals with no error; ctx expiry returns ctx.Err.
func (*Client) WaitReady ¶
WaitReady waits for the validated ServerReady exchange, session termination, or ctx cancellation. Run must be started separately. A terminated session returns FailedPrecondition, including when it was previously ready; this method does not retain or expose the handshake's potentially sensitive error. Cancellation returns ctx.Err(). Readiness is a snapshot, not a lease on the connection: a later Call can still observe a disconnect.
type ClientConfig ¶
type ClientConfig struct {
// Prepare runs once before OpenClient returns, before any transport I/O.
// It can attach optional profiles with NewRecoveryClient even when a
// connection factory owns Run. An error closes the partially built client.
Prepare func(*Client) error
// MinVersion/MaxVersion bound the proposed handshake range. Zero
// selects the binding singleton (v1). Min must not exceed Max.
MinVersion uint32
// MaxVersion is the proposed maximum; the hello frame carries it.
MaxVersion uint32
// Credential is the opaque hello credential. Empty is an attempt
// subject to host policy, not a parse error; oversize fails fast.
// OpenClient copies it; callers retain ownership of their input buffer.
// Go credential references are released after hello emission or Close.
Credential []byte
// DefaultTimeout applies when a call passes timeoutMs zero. Zero
// selects DefaultRPCTimeout. Values must be positive and at most 24h;
// the effective call budget is clamped by MaxTimeout.
DefaultTimeout time.Duration
// MaxConcurrent caps outstanding calls. Zero selects
// DefaultConcurrentRPCs; supported values are 16..1024. Excess calls fail fast
// with ResourceExhausted.
MaxConcurrent int
// NotifyBuffer sizes the notification queue (1..1024). Zero selects 256.
// Overflow drops the newest notification and counts it (see
// DroppedNotifications).
NotifyBuffer int
// WriterCapacity bounds queued plus active output frames. Zero selects 256.
WriterCapacity int
// MaxTimeout clamps requested call budgets. Zero selects 120 seconds.
MaxTimeout time.Duration
// HandshakeTimeout bounds the complete hello/ready exchange. Zero selects 5s.
HandshakeTimeout time.Duration
}
ClientConfig configures a Client session.
type ClientHello ¶
type ClientHello = syntrav1.ClientHello
ClientHello presents opaque credentials (handshake.proto).
type CommitUnknown ¶
type CommitUnknown struct{}
CommitUnknown means a write may have become durable. Reload and reconcile on a fresh connection; neither confirm nor blindly retry the application write.
func (*CommitUnknown) Code ¶
func (*CommitUnknown) Code() ErrorCode
func (*CommitUnknown) Error ¶
func (*CommitUnknown) Error() string
type CommittedPosition ¶
CommittedPosition is the last confirmed position for one stream.
type ConfirmedLease ¶
ConfirmedLease is the host-confirmed bounded lease.
func NegotiateLease ¶
func NegotiateLease(p LeaseProposal) (ConfirmedLease, error)
NegotiateLease applies host defaults, clamps, and enforces keepalive < idle.
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection is the stateful handshake machine for one side of a transport. It wraps the pure NextState transition with a mutex so concurrent read and write loops cannot interleave hello and close. Callers that prefer explicit control flow can use NextState directly and skip Connection entirely; both enforce the same six-state set. The bound principal is an opaque host-defined string (never client bytes); identity verification lives in the host's CredentialPolicy.
func NewConnection ¶
func NewConnection(cfg HandshakeConfig) (*Connection, error)
NewConnection returns a Connection in StateConnected. A misconfigured range fails fast here rather than at the first hello.
func (*Connection) AuthFailure ¶
func (c *Connection) AuthFailure() error
AuthFailure moves StateAuthenticating to StateClosing: the credential was presented but rejected, so no app frames were ever allowed.
func (*Connection) AuthSuccess ¶
func (c *Connection) AuthSuccess(principal string) error
AuthSuccess binds principal and advances StateAuthenticating to StateActive. An empty principal fails fast without mutating state: an anonymous activation would violate the ServerReady binding contract.
func (*Connection) BeginAuth ¶
func (c *Connection) BeginAuth() error
BeginAuth advances StateNegotiating to StateAuthenticating when credential verification starts. It is separate from OnHello so the caller can rate-limit or async-dispatch verification without holding the handshake mutex across I/O.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close initiates the drain from any non-terminal state into StateClosing. Closing from CLOSING is idempotent; closing from CLOSED is an error so double-close bugs surface instead of passing.
func (*Connection) MarkClosed ¶
func (c *Connection) MarkClosed() error
MarkClosed moves StateClosing to the terminal StateClosed once the drain completes. It is the only path into CLOSED; every other state must pass through Close first so in-flight RPCs are never dropped without a drain.
func (*Connection) OnHello ¶
func (c *Connection) OnHello(h *ClientHello) (uint32, error)
OnHello handles a ClientHello in StateConnected: it validates the hello, negotiates the highest overlap against the configured range, and advances to StateNegotiating. Any other state, a malformed hello, or a disjoint range leaves the state unchanged so the caller can divert to CLOSING.
func (*Connection) Principal ¶
func (c *Connection) Principal() string
Principal returns the principal bound at activation, or "" before.
func (*Connection) State ¶
func (c *Connection) State() ConnectionState
State returns the current connection state.
func (*Connection) Version ¶
func (c *Connection) Version() uint32
Version returns the negotiated version, or 0 before negotiation.
type ConnectionState ¶
type ConnectionState int
ConnectionState is the Syntra connection lifecycle state (SNTR-HS-001). Only six states exist; no shortcut such as CONNECTED to ACTIVE is permitted.
const ( // StateConnected means transport is up with no Syntra bytes exchanged. StateConnected ConnectionState = iota // StateNegotiating means hello was sent and version is under review. StateNegotiating ConnectionState = iota // StateAuthenticating means version overlap was found and credential policy runs. StateAuthenticating ConnectionState = iota // StateActive means handshake completed and RPCs plus notifications are legal. StateActive ConnectionState = iota // StateClosing means graceful close is in progress; no new RPCs are accepted. StateClosing ConnectionState = iota // StateClosed means transport is released and per-connection state is discarded. StateClosed ConnectionState = iota )
func NextState ¶
func NextState(current ConnectionState, kind BodyKind) (ConnectionState, error)
NextState validates one handshake transition. It enforces the six-state machine: unexpected messages before ACTIVE fail with FailedPrecondition, a second hello fails, and re-handshake on the same connection is forbidden. The caller owns timer and transport-close behavior.
func (ConnectionState) String ¶
func (s ConnectionState) String() string
String returns the diagnostic name for s.
type ControlBounds ¶
type ControlBounds struct {
MaxSessions int
MaxRetainedResults int // Shared pending + retained count per session.
MaxRetainedBytes int // Shared owned method/payload + terminal outcome bytes.
MaxTombstones int
MaxResumeCredentials int
MaxControlQueue int
MaxControlBytes int
ResultRetention time.Duration
TombstoneRetention time.Duration
ResumeLifetime time.Duration
}
ControlBounds documents every reliable-session bound.
func DefaultControlBounds ¶
func DefaultControlBounds() ControlBounds
DefaultControlBounds returns the normative v1 defaults.
type CredentialPolicy ¶
CredentialPolicy authenticates an opaque credential and returns the principal string to bind at ServerReady. Implementations own identity: this binding never interprets credential bytes beyond the size bound. An empty credential is an attempt subject to host policy: policies may accept it for anonymous-intent deployments or reject it with Unauthenticated. The credential bytes and any derived token must never be logged. Implementations should accept ctx with a bounded budget and return Unauthenticated for rejections vs Internal for verifier outages so the handshake can distinguish policy denial from downstream failure.
func StaticPolicy ¶
func StaticPolicy(principal string, allowEmpty bool) CredentialPolicy
StaticPolicy returns a CredentialPolicy that accepts any credential and binds principal. It is intended for tests, examples, and anonymous-intent deployments; production hosts MUST verify credentials against their identity system. When allowEmpty is false, empty credentials are rejected as Unauthenticated.
type DeliveryID ¶
type DeliveryID [deliveryIDLen]byte
DeliveryID is a 16-byte stable delivery key, distinct from request_id.
func ValidateDeliveryID ¶
func ValidateDeliveryID(id []byte) (DeliveryID, error)
ValidateDeliveryID checks 16 non-zero bytes.
type DuplicateCache ¶
type DuplicateCache struct {
// contains filtered or unexported fields
}
DuplicateCache is a bounded FIFO cache of recently confirmed result keys. A hit answers a duplicate without re-applying effects; a miss goes through the normal persist/confirm path. Insertion beyond capacity evicts the oldest entry first. It never grows without bound.
func NewDuplicateCache ¶
func NewDuplicateCache(capacity int) *DuplicateCache
NewDuplicateCache returns a cache holding at most capacity keys. Zero capacity caches nothing.
func (*DuplicateCache) Contains ¶
func (c *DuplicateCache) Contains(key []byte) bool
Contains reports whether key was recently confirmed and retained.
func (*DuplicateCache) Insert ¶
func (c *DuplicateCache) Insert(key []byte)
Insert records a confirmed result. Duplicate inserts are no-ops. Beyond capacity the oldest entry is evicted first.
func (*DuplicateCache) Len ¶
func (c *DuplicateCache) Len() int
Len returns entries currently retained.
type DurableRecord ¶
func (DurableRecord) GoString ¶
func (r DurableRecord) GoString() string
func (DurableRecord) Position ¶
func (r DurableRecord) Position() *ExpectedPosition
func (DurableRecord) String ¶
func (r DurableRecord) String() string
type DurableStore ¶
type DurableStore interface {
Load(stream string) *CommittedPosition
StoreAtomic(pos CommittedPosition, effectsDigest []byte) error
}
DurableStore is a position/metadata helper. An effects digest does not persist application effects. Use RecoveryPersistence for full-state recovery commits.
type ErrorCode ¶
ErrorCode is the error registry (errors.proto).
const ( // ErrorCodeUnspecified is not a valid failure outcome (SNTR-ERR-001). ErrorCodeUnspecified ErrorCode = syntrav1.ErrorCode_ERROR_CODE_UNSPECIFIED // ErrorCodeCancelled indicates cancellation. ErrorCodeCancelled ErrorCode = syntrav1.ErrorCode_ERROR_CODE_CANCELLED // ErrorCodeUnknown indicates an unclassified failure. ErrorCodeUnknown ErrorCode = syntrav1.ErrorCode_ERROR_CODE_UNKNOWN // ErrorCodeInvalidArgument indicates invalid arguments or envelope shape. ErrorCodeInvalidArgument ErrorCode = syntrav1.ErrorCode_ERROR_CODE_INVALID_ARGUMENT // ErrorCodeDeadlineExceeded indicates budget expiry, not rollback. ErrorCodeDeadlineExceeded ErrorCode = syntrav1.ErrorCode_ERROR_CODE_DEADLINE_EXCEEDED // ErrorCodeNotFound indicates a missing target. ErrorCodeNotFound ErrorCode = syntrav1.ErrorCode_ERROR_CODE_NOT_FOUND // ErrorCodeAlreadyExists indicates a creation conflict. ErrorCodeAlreadyExists ErrorCode = syntrav1.ErrorCode_ERROR_CODE_ALREADY_EXISTS // ErrorCodePermissionDenied indicates insufficient access. ErrorCodePermissionDenied ErrorCode = syntrav1.ErrorCode_ERROR_CODE_PERMISSION_DENIED // ErrorCodeResourceExhausted indicates an exhausted resource budget. ErrorCodeResourceExhausted ErrorCode = syntrav1.ErrorCode_ERROR_CODE_RESOURCE_EXHAUSTED // ErrorCodeFailedPrecondition indicates an operation cannot currently run. ErrorCodeFailedPrecondition ErrorCode = syntrav1.ErrorCode_ERROR_CODE_FAILED_PRECONDITION // ErrorCodeAborted indicates an aborted sequence. ErrorCodeAborted ErrorCode = syntrav1.ErrorCode_ERROR_CODE_ABORTED // ErrorCodeOutOfRange indicates a value outside the supported range. ErrorCodeOutOfRange ErrorCode = syntrav1.ErrorCode_ERROR_CODE_OUT_OF_RANGE // ErrorCodeUnimplemented indicates an unknown method or unsupported feature. ErrorCodeUnimplemented ErrorCode = syntrav1.ErrorCode_ERROR_CODE_UNIMPLEMENTED // ErrorCodeInternal indicates an internal failure. ErrorCodeInternal ErrorCode = syntrav1.ErrorCode_ERROR_CODE_INTERNAL ErrorCodeUnavailable ErrorCode = syntrav1.ErrorCode_ERROR_CODE_UNAVAILABLE // ErrorCodeDataLoss indicates unrecoverable corruption or loss. ErrorCodeDataLoss ErrorCode = syntrav1.ErrorCode_ERROR_CODE_DATA_LOSS // ErrorCodeUnauthenticated indicates missing or unaccepted credentials. ErrorCodeUnauthenticated ErrorCode = syntrav1.ErrorCode_ERROR_CODE_UNAUTHENTICATED )
ErrorCode registry aliases. Values 0..16 match the IDL exactly.
func NormalizeErrorCode ¶
NormalizeErrorCode maps any received int32 to the registry, returning ErrorCodeUnknown for numbers outside 0..16 (SNTR-ERR-005). Generated enum getters alone do not implement that policy, so every decode path must normalize before branching.
func SignalCode ¶
func SignalCode(s SessionSignal) ErrorCode
SignalCode maps a signal to its existing wire code (no new codes).
type ExecutionBudget ¶
type ExecutionBudget struct {
// contains filtered or unexported fields
}
ExecutionBudget bounds callbacks still executing, independently of protocol correlation. Share one budget across replacement Host instances when they share application resources. A cancelled or closed call retains its charge until its callback actually returns.
func NewExecutionBudget ¶
func NewExecutionBudget(capacity int) (*ExecutionBudget, error)
NewExecutionBudget creates a nonblocking callback budget of 1..1024 slots.
func (*ExecutionBudget) Live ¶
func (b *ExecutionBudget) Live() int
Live reports callbacks and recovery egress workers which have not returned, including abandoned work.
type ExpectedPosition ¶
func (ExpectedPosition) GoString ¶
func (r ExpectedPosition) GoString() string
func (ExpectedPosition) String ¶
func (r ExpectedPosition) String() string
type Frame ¶
Frame is the versioned Syntra envelope (envelope.proto).
func NewCancelFrame ¶
NewCancelFrame builds a cancel Frame with nonzero correlation.
func NewHelloFrame ¶
func NewHelloFrame(hello *ClientHello, maxVersion uint32) *Frame
NewHelloFrame builds a hello Frame with the proposed maximum version.
func NewNotificationFrame ¶
func NewNotificationFrame(version uint32, n *Notification) *Frame
NewNotificationFrame builds a notification Frame (request_id zero).
func NewReadyFrame ¶
func NewReadyFrame(version uint32, ready *ServerReady) *Frame
NewReadyFrame builds a ready Frame at the negotiated version.
func NewRequestFrame ¶
func NewRequestFrame(version uint32, requestID uint64, req *RpcRequest) *Frame
NewRequestFrame builds a request Frame with nonzero correlation.
func NewResultFrame ¶
NewResultFrame builds a result Frame with nonzero correlation.
func UnmarshalFrame ¶
UnmarshalFrame decodes exactly one Frame from data. It rejects empty inputs, trailing bytes, reserved top-level numbers 16/17, and duplicate bodies before running structural validation. Duplicate version/request_id occurrences are type-checked but follow protobuf merge semantics (last wins). Cancel inner bytes and nested unassigned numbers are tolerated as unknown fields per SNTR-SER-003. Request methods are validated by the host so malformed methods receive per-RPC errors. proto.Unmarshal owns decoding; the pre-scan owns protocol strictness the generated codec does not enforce (reserved 16/17 and duplicate body alternatives). Unknown fields alongside a known body remain forward-compatible metadata.
type FrameReceipt ¶
type FrameReceipt struct {
// contains filtered or unexported fields
}
FrameReceipt is trusted local timing supplied by a transport, never wire data. Capture it before synchronous assembly of a completing batch and retain the same value for every frame completed by that batch, including fragmented frames. Its zero value is invalid. It conveys timing only, not identity or authority.
func CaptureFrameReceipt ¶
func CaptureFrameReceipt(clock TerminalClock) FrameReceipt
CaptureFrameReceipt samples trusted elapsed time FIRST and scheduler time SECOND. Suspension between the samples can shorten but never renew a budget. clock may be nil for scheduler-only custom transports; it must otherwise be the transport's original trusted suspend-inclusive clock, not a reconstructed one.
func RecvWithReceipt ¶
RecvWithReceipt calls t.Recv and returns its frame with correlated local timing. It never dispatches an optional RecvWithReceipt method that embedding could promote past a wrapper's Recv policy. A nil transport returns InvalidArgument.
The call is synchronous and propagates ctx cancellation, deadline and values; t.Recv must honor cancellation. Metadata capture is bounded and scoped to this call, closes on return, and forwards its matched receipt to any enclosing SDK receive. Copying or buffering wrappers can retain the returned receipt and Publish it with their returned buffer into that outer receive's context.
Receipts are trusted SDK-local transport metadata, never peer-supplied timing. This helper grants no identity, authorization or terminal capability. For legacy transports publishing no metadata, it captures delivery timing only; unavailable assembly and buffering timing cannot be inferred.
func (FrameReceipt) ElapsedAge ¶
func (r FrameReceipt) ElapsedAge() time.Duration
ElapsedAge returns the original trusted age, for driver assembly cutoffs. It is meaningful only on the clock supplied to CaptureFrameReceipt, with valid continuity.
func (FrameReceipt) Publish ¶
func (r FrameReceipt) Publish(ctx context.Context, frame []byte)
Publish associates this receipt with frame in the SDK's current receive call. Trusted drivers call it before returning the owned buffer from Recv (or RecvWithReceipt). Outside an SDK receive it is a no-op. Forward the receive context through wrappers; the root always calls the outer Recv, never an optional method that embedding could promote past that wrapper's checks.
Correlation requires the same buffer, length and contents. A wrapper that copies or transforms a frame must explicitly publish its original receipt for the new buffer; it must not recapture time. Wrappers buffering across calls must retain and publish the original receipt when returning the buffered frame. Use the package-level RecvWithReceipt helper to obtain the inner receipt while preserving the inner transport's ordinary Recv policy. Only the most recent 32 publications per call are retained. An unmatched or evicted frame fails closed if any metadata was published, rather than receiving a fresh delivery-time budget. Publication is synchronized, but the caller must own frame while publishing and returning it. Empty or oversized publications disable fallback but are not hashed or retained; closed receives ignore them.
func (FrameReceipt) ReceivedAt ¶
func (r FrameReceipt) ReceivedAt() time.Time
ReceivedAt returns the original scheduler timestamp, not the delivery time.
type FrameReceiptTransport ¶
type FrameReceiptTransport interface {
Transport
// RecvWithReceipt returns the next frame and its completing-batch origin.
// Error returns must not expose a frame; successful receipts must be nonzero.
RecvWithReceipt(context.Context) ([]byte, FrameReceipt, error)
}
FrameReceiptTransport returns a frame and its original timing in ONE receive operation for direct SDK consumers. Implementations must serialize queue removal with its metadata and Publish the pair to ctx for root SDK receives. The root does not detect this interface: Recv must preserve receive policy and publish metadata itself (it may delegate to its own RecvWithReceipt). Legacy Recv-only transports remain supported, but their unavailable assembly and buffering timing cannot be inferred: capture occurs after Recv returns.
type HandlerFunc ¶
type HandlerFunc func(ctx context.Context, req *RpcRequest) (*RpcResult, error)
HandlerFunc implements one application method for a Host. It receives the validated RpcRequest with ctx bounded by the effective call budget (cancellation propagates client cancel frames and conn teardown). It returns either a valid *RpcResult or an error: a *RpcError becomes the wire error outcome; any other error becomes a generic INTERNAL outcome so handler internals never leak to the peer (SNTR-ERR-003). Returning (nil, nil) is a handler bug and is reported as INTERNAL.
type HandshakeConfig ¶
type HandshakeConfig struct {
// ServerMinVersion is the lowest version the local side accepts.
ServerMinVersion uint32
// ServerMaxVersion is the highest version the local side emits.
ServerMaxVersion uint32
}
HandshakeConfig carries the local supported version range. The zero value selects the binding singleton (v1); construct via NewHandshakeConfig so the fail-fast range check cannot be skipped.
func NewHandshakeConfig ¶
func NewHandshakeConfig(cfg HandshakeConfig) (HandshakeConfig, error)
NewHandshakeConfig validates the version range up front, defaulting zero fields to the binding singleton.
type Host ¶
type Host struct {
// contains filtered or unexported fields
}
Host is a responder-side Syntra session factory. The zero value is invalid; construct with OpenHost. A Host is safe for concurrent Serve calls (one per connection) and NotifyAll broadcasts.
func OpenHost ¶
func OpenHost(cfg HostConfig) (*Host, error)
OpenHost creates a responder session factory. It validates the config and opens nothing per connection yet; each Serve call opens and closes exactly one core.
func (*Host) Close ¶
Close releases the factory: new Serve calls fail fast and served connections are closed and their handlers observe ctx cancellation. A second Close reports FailedPrecondition. Close signals shutdown without waiting; callers join Serve for its bounded drain, then Wait for retained callbacks and recovery egress to actually exit. Terminal authority callbacks may call Close: terminal carriers are interrupted without joining the active observer, and their actual close join remains owned until Wait/Done completes.
func (*Host) DisconnectPrincipal ¶
DisconnectPrincipal cancels and closes every current connection bound to principal, including idle connections that only receive pushes. It does not prevent future authentication; the authentication policy must reject revoked identities. An empty principal matches no connection. On a terminal connection this interrupts without joining a possibly reentrant authority callback; the retained join is included in Host.Wait/Done after Host.Close. It is still an immediate abort, never a receipt drain.
func (*Host) Done ¶
func (h *Host) Done() <-chan struct{}
Done closes after Close and all served connections, callbacks, and recovery egress have actually exited, including work retained after Serve returns.
func (*Host) NotifyAll ¶
NotifyAll enqueues payload as a notification on every served connection. With no connections it is a documented no-op. Payloads MUST be opaque application bytes; empty is a valid empty event. Success acknowledges queue admission, not transport or peer delivery. Partial-delivery failures are combined and returned; RpcError values remain unwrappable via errors.As. Only connections with a successful enqueue are signaled.
func (*Host) NotifyDirected ¶
NotifyDirected enqueues payload as a notification on exactly the served connections bound to principal. Connections bound to other principals never observe it (directed delivery isolation for recovery batches and per-stream signals). With no matching connections it is a documented no-op. Partial-delivery failures are combined and returned; RpcError values remain unwrappable via errors.As. Only connections with a successful enqueue are signaled. Recovery drivers MUST use this (or a subscription-handle-routed variant above it) instead of NotifyAll broadcast: broadcast leaks stream state across principals and breaks per-stream termination scope.
func (*Host) Serve ¶
Serve runs one connection on t: exactly one ClientHello first, exactly one terminal handshake outcome (ServerReady or handshake error + close), then validated dispatch until ctx ends, the transport fails, a fatal protocol violation arrives, or the Host closes. Unknown methods answer UNIMPLEMENTED; handler failures answer their mapped code; the connection stays usable. When HostConfig.Authorize is set it is checked with the bound principal before handler effects on every call; denials answer generic Unauthenticated/PermissionDenied. PermissionDenied keeps the connection usable; Unauthenticated (expired/revoked binding) cancels callbacks, attempts a bounded drain of the per-RPC error, then closes per SNTR-AUTH-008/SNTR-ASEC-006. A nil Authorize denies every method. ctx end cancels in-flight handlers and closes the connection. Serve returns nil on a clean handshake-completed close and the fatal error otherwise. The entire handshake, including Policy, has a five-second deadline shortened by ctx. Policy and Transport must honor their contexts. Serve owns t and closes it on every terminal path. Transport.Recv MUST return promptly when its context ends; teardown waits at most handlerShutdownGrace for a violating Recv before abandoning the pump (the leaked Recv goroutine exits when Recv finally returns). On teardown Serve cancels callbacks and drains completions for up to one second; callbacks that ignore cancellation cannot send a late result or access the closed connection core.
type HostConfig ¶
type HostConfig struct {
// TerminalMethods enables only explicitly listed request-owned retirement
// operations. Nil is disabled. The transport must independently opt in.
TerminalMethods map[string]TerminalMethodPolicy
// MinVersion/MaxVersion bound the accepted handshake range. Zero
// selects the binding singleton (v1).
MinVersion uint32
// MaxVersion is the highest version the host emits.
MaxVersion uint32
// Policy verifies hello credentials and returns the principal to
// bind when ChannelPolicy is unset. Nil denies these handshakes as
// Unauthenticated.
Policy CredentialPolicy
// ChannelPolicy verifies a freshly confirmed transport channel identity and
// hello credential. When set, it replaces Policy and requires a confirmed
// ChannelIdentityProvider. It must return a nonempty principal.
ChannelPolicy ChannelPolicy
// Handler dispatches authorized, validated requests. Nil answers authorized
// requests UNIMPLEMENTED (no method is known).
Handler HandlerFunc
// Recovery enables connection-bound update recovery after authentication.
// Normal Authorize policy still runs before every recovery operation.
Recovery *RecoveryService
// Authorize is the per-method policy evaluated with the bound principal
// before handler effects. Nil selects DenyAllAuthorize.
Authorize AuthorizeFunc
// RequestBudget optionally caps live application requests before Authorize. Nil
// preserves wire/default/MaxTimeout selection. See RequestBudgetFunc for the
// pure, prompt selector contract and zero/negative duration semantics.
RequestBudget RequestBudgetFunc
// DefaultTimeout applies when a request passes timeoutMs zero. Zero
// selects DefaultRPCTimeout. Values must be positive and at most 24h;
// the effective call budget is clamped by MaxTimeout.
DefaultTimeout time.Duration
// MaxConcurrent caps outstanding calls per connection. Zero selects
// DefaultConcurrentRPCs. Supported values are 16..1024; larger values fail as
// InvalidArgument. Excess calls fail with ResourceExhausted while
// the connection stays usable.
MaxConcurrent int
// WriteTimeout bounds each post-handshake transport Send. Zero selects
// ten seconds. A failed or timed-out write terminates the connection.
// One writer sends FIFO snapshots independently of the session loop.
// Queued plus active writes are capped at 256 frames and 8 MiB per
// connection; saturation terminates Serve with RESOURCE_EXHAUSTED.
// Transports must honor their contexts and interrupt I/O on Close.
WriteTimeout time.Duration
// MaxTimeout clamps requested call budgets. Zero selects 120 seconds.
MaxTimeout time.Duration
// HandshakeTimeout bounds hello, authentication, and ready. Zero selects 5s.
HandshakeTimeout time.Duration
// WriterCapacity bounds queued plus active writer frames. Zero selects 256.
WriterCapacity int
// ExecutionBudget bounds authentication, handlers, and recovery egress workers
// across all connections served by this factory. Nil uses the process-wide
// 1024-slot budget. External work spawned by a callback must be joined before return.
ExecutionBudget *ExecutionBudget
}
HostConfig configures a Host session factory. Each Serve call opens one independent per-connection core from this config.
type LeaseProposal ¶
LeaseProposal is the client-proposed keepalive lease (zero = host default).
type MemoryRecoveryStore ¶
type MemoryRecoveryStore struct {
// contains filtered or unexported fields
}
MemoryRecoveryStore is a bounded, concurrency-safe reference. It is NOT durable.
func NewMemoryRecoveryStore ¶
func NewMemoryRecoveryStore(l RecoveryStoreLimits) (*MemoryRecoveryStore, error)
func (*MemoryRecoveryStore) Commit ¶
func (s *MemoryRecoveryStore) Commit(ctx context.Context, scope PersistenceScope, expected *ExpectedPosition, r DurableRecord) error
func (*MemoryRecoveryStore) FailNextCommit ¶
func (s *MemoryRecoveryStore) FailNextCommit()
func (*MemoryRecoveryStore) Load ¶
func (s *MemoryRecoveryStore) Load(ctx context.Context, scope PersistenceScope) (*DurableRecord, error)
type MemoryStore ¶
type MemoryStore struct {
FailNext bool
FailAlways bool
MaxRecords int
// contains filtered or unexported fields
}
MemoryStore is a bounded volatile position/metadata helper, not durable storage. FailNext injects exactly one Unavailable failure on the next write; FailAlways fails every write until cleared.
func (*MemoryStore) Load ¶
func (s *MemoryStore) Load(stream string) *CommittedPosition
Load returns the last recorded position for stream, or nil. The returned position deep-copies committed bytes so callers can never alias (or mutate) store state.
func (*MemoryStore) StoreAtomic ¶
func (s *MemoryStore) StoreAtomic(pos CommittedPosition, effectsDigest []byte) error
StoreAtomic records pos and effectsDigest atomically, or records nothing on injected failure. The caller must not confirm on error. Both the position's committed bytes and the digest are deep-copied so later caller mutation cannot alias retained state. Recording a digest is not persistence of effects.
type Notification ¶
type Notification = syntrav1.Notification
Notification carries uncorrelated opaque data (events.proto).
type PersistenceError ¶
type PersistenceError uint8
const ( PersistenceCorrupt PersistenceConflict PersistenceOverLimit )
func (PersistenceError) Code ¶
func (e PersistenceError) Code() ErrorCode
func (PersistenceError) Error ¶
func (e PersistenceError) Error() string
type PersistenceScope ¶
type PersistenceScope struct{ Principal, Stream string }
PersistenceScope binds state to the application's principal namespace and stable stream. These labels are not authentication credentials.
func (PersistenceScope) GoString ¶
func (s PersistenceScope) GoString() string
func (PersistenceScope) String ¶
func (s PersistenceScope) String() string
type QueuedSignal ¶
type QueuedSignal struct {
ID SessionID
Signal SessionSignal
}
QueuedSignal is one buffered lifecycle signal for a session.
type ReconcileOutcome ¶
type ReconcileOutcome string
ReconcileOutcome describes retained delivery state.
const ( ReconcileRetained ReconcileOutcome = "retained" ReconcileForgotten ReconcileOutcome = "forgotten" ReconcileUnknown ReconcileOutcome = "unknown" ReconcilePending ReconcileOutcome = "pending" )
type ReconcilerConfig ¶
type ReconcilerConfig struct {
// TickInterval is the minimum interval between ticks.
TickInterval time.Duration
// MaxStreamsPerTick caps streams that may report per tick.
MaxStreamsPerTick int
// MaxStreams bounds retained observations. Zero selects 256.
MaxStreams int
}
ReconcilerConfig bounds checkpoint reconciliation.
type RecoveryClient ¶
type RecoveryClient struct {
// contains filtered or unexported fields
}
RecoveryClient binds one authenticated connection and application persistence namespace. Methods serialize stop-and-wait work; ingress is independently bounded. Construction attaches one immutable inbox before Client.Run. Close the connection when replacing identity context.
func NewRecoveryClient ¶
func NewRecoveryClient(c *Client, principalScope string, store RecoveryPersistence, l RecoveryLimits) (*RecoveryClient, error)
func (*RecoveryClient) CatchUp ¶
func (c *RecoveryClient) CatchUp(ctx context.Context, request *pb.RecoveryCatchUpRequest) (*pb.RecoveryCatchUpAccepted, error)
func (*RecoveryClient) Close ¶
func (c *RecoveryClient) Close()
func (*RecoveryClient) Confirm ¶
func (c *RecoveryClient) Confirm(ctx context.Context, request *pb.RecoveryConfirmRequest) (*pb.RecoveryConfirmResponse, error)
func (*RecoveryClient) Inbox ¶
func (c *RecoveryClient) Inbox() *RecoveryInbox
func (*RecoveryClient) Negotiate ¶
func (c *RecoveryClient) Negotiate(ctx context.Context, request *pb.RecoveryNegotiateRequest) (*pb.RecoveryNegotiateResponse, error)
func (*RecoveryClient) NextEvent ¶
func (c *RecoveryClient) NextEvent(ctx context.Context, handle []byte) (*RecoveryEvent, error)
NextEvent offers at most one batch until Persist and Confirm complete. Terminal controls take precedence over pending work and never manufacture a generation. One consumer may wait per handle; idle waits release the client operation gate.
func (*RecoveryClient) Persist ¶
func (c *RecoveryClient) Persist(ctx context.Context, handle, state []byte) error
Persist commits the pending offer with full application state. It never sends Confirm. Failure leaves the offer pending; CommitUnknown fences the connection.
func (*RecoveryClient) Progress ¶
func (c *RecoveryClient) Progress(ctx context.Context, handle []byte) (RecoveryProgress, error)
func (*RecoveryClient) Replay ¶
func (c *RecoveryClient) Replay(ctx context.Context, request *pb.RecoveryReplayRequest) (*pb.RecoveryReplayPage, error)
func (*RecoveryClient) SnapshotBytes ¶
SnapshotBytes returns the complete opaque transfer for application installation.
func (*RecoveryClient) SnapshotConfirm ¶
func (c *RecoveryClient) SnapshotConfirm(ctx context.Context, request *pb.RecoverySnapshotConfirmRequest) (*pb.RecoverySnapshotInstalled, error)
func (*RecoveryClient) SnapshotFetch ¶
func (c *RecoveryClient) SnapshotFetch(ctx context.Context, request *pb.RecoverySnapshotFetchRequest) (*pb.RecoverySnapshotChunk, error)
func (*RecoveryClient) SnapshotOffer ¶
func (c *RecoveryClient) SnapshotOffer(ctx context.Context, request *pb.RecoverySnapshotOfferRequest) (*pb.RecoverySnapshotDescriptor, error)
func (*RecoveryClient) Subscribe ¶
func (c *RecoveryClient) Subscribe(ctx context.Context, request *pb.RecoverySubscribeRequest, stableStream []byte, intent RecoverySubscribeIntent) (*RecoverySubscription, error)
Subscribe binds the typed request to the loaded full-state record. The stable stream label is application-resolved; selectors and handles are not identities.
func (*RecoveryClient) Unsubscribe ¶
func (c *RecoveryClient) Unsubscribe(ctx context.Context, request *pb.RecoveryUnsubscribeRequest) (*pb.RecoveryUnsubscribeResponse, error)
type RecoveryConnection ¶
RecoveryConnection is supplied only from the authenticated ACTIVE session.
type RecoveryEvent ¶
type RecoveryEvent struct {
Batch *pb.RecoveryBatch
CaughtUp bool
InitialLiveBaseline []byte
Trailer *pb.RecoveryBatchTrailer
}
type RecoveryHook ¶
type RecoveryHook string
const ( RecoveryHookSubscribe RecoveryHook = "subscribe" RecoveryHookReplay RecoveryHook = "replay" RecoveryHookCatchUp RecoveryHook = "catch-up" RecoveryHookConfirm RecoveryHook = "confirm" RecoveryHookSnapshotOffer RecoveryHook = "snapshot-offer" RecoveryHookSnapshotFetch RecoveryHook = "snapshot-fetch" RecoveryHookSnapshotConfirm RecoveryHook = "snapshot-confirm" RecoveryHookUnsubscribe RecoveryHook = "unsubscribe" RecoveryHookEmit RecoveryHook = "emit" )
type RecoveryHostSession ¶
type RecoveryHostSession struct {
// contains filtered or unexported fields
}
RecoveryHostSession owns exactly one connection's negotiation and handle space. The parent calls Handler for admitted RPCs, drains NextNotification through its bounded ordered writer, and calls Close on every teardown path.
func RecoveryHostSessionFromContext ¶
func RecoveryHostSessionFromContext(ctx context.Context) (*RecoveryHostSession, bool)
RecoveryHostSessionFromContext returns the runtime-owned connection binding supplied to host callbacks. A source can retain this handle for connection- scoped Publish calls; each call still revalidates authority and session state.
func (*RecoveryHostSession) Close ¶
func (h *RecoveryHostSession) Close()
func (*RecoveryHostSession) Err ¶
func (h *RecoveryHostSession) Err() error
Err reports principal withdrawal before ordinary connection shutdown.
func (*RecoveryHostSession) Handle ¶
func (h *RecoveryHostSession) Handle(ctx context.Context, method string, payload []byte) (result []byte, resultErr error)
Handle accepts profile payloads only after the parent has admitted the RPC.
func (*RecoveryHostSession) Handler ¶
func (h *RecoveryHostSession) Handler(ctx context.Context, req *RpcRequest) (*RpcResult, error)
func (*RecoveryHostSession) NextNotification ¶
func (h *RecoveryHostSession) NextNotification(ctx context.Context) (result []byte, resultErr error)
func (*RecoveryHostSession) PopNotification ¶
func (h *RecoveryHostSession) PopNotification(ctx context.Context) (result []byte, resultErr error)
func (*RecoveryHostSession) Publish ¶
func (h *RecoveryHostSession) Publish(ctx context.Context, identity []byte, b RecoveryStoredBatch) (resultErr error)
Publish targets this authenticated connection's subscriptions for stable S. Publication and Capture must share the application's ordering boundary.
func (*RecoveryHostSession) RevalidateNotification ¶
func (h *RecoveryHostSession) RevalidateNotification(ctx context.Context, payload []byte) error
RevalidateNotification is called immediately before ordered writer admission.
func (*RecoveryHostSession) Revoked ¶
func (h *RecoveryHostSession) Revoked() bool
Revoked is sticky for this authenticated connection, including after Close. Runtime dispatch must inspect it independently of a selected RPC deadline.
type RecoveryInbox ¶
type RecoveryInbox struct {
// contains filtered or unexported fields
}
RecoveryInbox routes before the generic lossy notification queue. Once enabled, it owns profile notifications; mixed protocols require explicit demultiplexing. It never calls application code. Retired handles remain bounded tombstones.
func NewRecoveryInbox ¶
func NewRecoveryInbox(l RecoveryLimits) (*RecoveryInbox, error)
func (*RecoveryInbox) Close ¶
func (i *RecoveryInbox) Close()
func (*RecoveryInbox) Counts ¶
func (i *RecoveryInbox) Counts() RecoveryInboxCounts
func (*RecoveryInbox) Enable ¶
func (i *RecoveryInbox) Enable() error
func (*RecoveryInbox) Enabled ¶
func (i *RecoveryInbox) Enabled() bool
func (*RecoveryInbox) Push ¶
func (i *RecoveryInbox) Push(payload []byte) error
Push is called only for authenticated, ACTIVE, validated envelope payloads. Invalid profile bytes fail closed, rather than falling through to another queue.
type RecoveryInboxCounts ¶
type RecoveryInboxCounts struct{ Handles, DataMessages, DataBytes, ControlMessages int }
type RecoveryLimits ¶
type RecoveryLimits struct {
SubscriptionsPerConnection, SubscriptionsPerPrincipal int
PendingRPCsPerConnection int
QueuedBytesPerStream, QueuedBytesPerConnection, QueuedMessagesPerStream int
ReplayBatches, ReplayBytes, SnapshotPageBytes, SnapshotPages int
MaxConnections, MaxConnectionsPerPrincipal, HandlesPerConnection int
RetainedReplyBytes, RetainedReplies, ReplyRetries int
DefaultDeadline, ReplyTTL time.Duration
}
func DefaultRecoveryLimits ¶
func DefaultRecoveryLimits() RecoveryLimits
func (RecoveryLimits) Validate ¶
func (l RecoveryLimits) Validate() error
type RecoveryPageBudget ¶
type RecoveryPageBudget struct{ MaxBatches, MaxEntryTotalBytes, MaxEntryBytes int }
type RecoveryPersistence ¶
type RecoveryPersistence interface {
Load(context.Context, PersistenceScope) (*DurableRecord, error)
Commit(context.Context, PersistenceScope, *ExpectedPosition, DurableRecord) error
}
RecoveryPersistence commits the FULL opaque state and its scoped position as one application persistence point. Nil expected requires absence. Exact full-record duplicates are no-ops even with a stale expected position. A cancelled commit that may have taken effect must return *CommitUnknown rather than rollback evidence.
type RecoveryProgress ¶
type RecoveryProgress struct{ LocallyDurable, ConfirmSent, PeerAcknowledged *ExpectedPosition }
RecoveryProgress observations are independent: submitted does not imply received.
type RecoveryProviderPage ¶
type RecoveryProviderPage struct {
Batches []RecoveryStoredBatch
Result, Marker []byte
}
type RecoveryProviderStream ¶
type RecoveryService ¶
type RecoveryService struct {
// contains filtered or unexported fields
}
func NewRecoveryService ¶
func NewRecoveryService(source RecoverySource, l RecoveryLimits) (*RecoveryService, error)
func (*RecoveryService) Handler ¶
func (s *RecoveryService) Handler(ctx context.Context, request *RpcRequest) (*RpcResult, error)
Handler is suitable for an explicitly configured generic Host handler. The caller supplies a connection-bound context and still performs normal RPC authorization. Unknown operations and missing bindings return Unimplemented.
func (*RecoveryService) OpenConnection ¶
func (s *RecoveryService) OpenConnection(c RecoveryConnection) (*RecoveryHostSession, error)
type RecoverySource ¶
type RecoverySource interface {
Authorize(context.Context, string, []byte, RecoveryHook) error
Capture(context.Context, string, []byte) (RecoveryProviderStream, error)
CurrentGeneration(context.Context, string, []byte) (uint64, error)
ValidateIssued(context.Context, string, RecoveryProviderStream, []byte) error
Replay(context.Context, string, RecoveryProviderStream, []byte, []byte, RecoveryPageBudget) (RecoveryProviderPage, error)
Snapshot(context.Context, string, RecoveryProviderStream) (RecoveryProviderSnapshot, error)
SnapshotPage(context.Context, string, RecoveryProviderStream, RecoveryProviderSnapshot, uint32) ([]byte, error)
}
RecoverySource is application-owned. Callbacks must be bounded, honor context, and must not reenter the session. Capture serializes publication at fixed B. ValidateIssued binds checkpoints to principal/stable stream/G independently of volatile reply caches and ordinary retention pruning, including after restart. Snapshot establishes the recoverable boundary/content binding before returning. Sources bound their own history and immutable snapshots in count, bytes and age.
type RecoveryStoreLimits ¶
type RecoveryStoreLimits struct{ MaxRecords, MaxStateBytes, MaxTotalBytes int }
func DefaultRecoveryStoreLimits ¶
func DefaultRecoveryStoreLimits() RecoveryStoreLimits
type RecoveryStoredBatch ¶
type RecoverySubscribeIntent ¶
type RecoverySubscribeIntent uint8
const ( RecoveryInitialLiveOnly RecoverySubscribeIntent = iota + 1 RecoveryResumeDurable RecoverySnapshotCurrentGeneration )
type RecoverySubscription ¶
type RecoverySubscription struct {
Response *pb.RecoverySubscribeResponse
Restored *DurableRecord
}
type ReliableManager ¶
type ReliableManager struct {
// contains filtered or unexported fields
}
ReliableManager is the bounded Go manager (sync, no goroutines, explicit drain).
func NewReliableManager ¶
func NewReliableManager(bounds ControlBounds) (*ReliableManager, error)
NewReliableManager constructs a bounded manager.
func (*ReliableManager) Attach ¶
func (m *ReliableManager) Attach(now time.Time, sid SessionID, resumeCred []byte, connectionID, principal string, version uint32, p LeaseProposal) (uint64, ConfirmedLease, string, []byte, error)
Attach binds a connection (fresh or resume with fencing + rotation). On resume it rotates the credential and returns the freshly generated resume credential for the next resume; callers must thread it forward. The fenced connection (if any) is returned for observability.
func (*ReliableManager) CheckIdle ¶
CheckIdle reports whether the session's active connection is past its idle timeout without mutating state.
func (*ReliableManager) CreateSession ¶
func (m *ReliableManager) CreateSession(now time.Time, principal string, version uint32, p LeaseProposal) (SessionID, uint64, []byte, ConfirmedLease, error)
CreateSession issues a fresh session (epoch 1 + fresh resume handle).
func (*ReliableManager) Detach ¶
func (m *ReliableManager) Detach(sid SessionID, connectionID string)
Detach clears the active connection when it matches (idempotent; unknown sessions are a no-op).
func (*ReliableManager) DrainForShutdown ¶
func (m *ReliableManager) DrainForShutdown() ([]SessionID, []QueuedSignal, int, error)
DrainForShutdown enters draining, detaches active connections, queues a going-away signal per detached session, and returns the drained session IDs with pending signals plus the count of signals dropped to a full queue. Dropped signals are reported, never swallowed.
func (*ReliableManager) DrainSignals ¶
func (m *ReliableManager) DrainSignals(limit int) []QueuedSignal
DrainSignals dequeues up to limit queued signals (bounded by MaxControlQueue, at least one when limit > 0).
func (*ReliableManager) Forget ¶
func (m *ReliableManager) Forget(sid SessionID, did DeliveryID) (bool, error)
Forget rejects live pending work, discards one retained outcome, and retains a bounded Forgotten marker (bounded by MaxRetainedResults, independent from MaxTombstones) so Reconcile reports Forgotten rather than Unknown. The marker retains the outcome's request digest when known so the live forgotten window still enforces duplicate-content validation. Clock behavior is the existing system clock for source compatibility; use ForgetAt for deterministic caller-clock tests.
func (*ReliableManager) ForgetAt ¶
func (m *ReliableManager) ForgetAt(now time.Time, sid SessionID, did DeliveryID) (bool, error)
ForgetAt is the clock-aware Forget sharing the same implementation.
func (*ReliableManager) NoteDispatch ¶
func (m *ReliableManager) NoteDispatch(now time.Time, sid SessionID, epoch uint64, did DeliveryID, method string, payload []byte) error
NoteDispatch validates the active attachment epoch and reserves owned method/payload metadata before dispatch. Identical duplicates are idempotent; callers must use Reconcile to distinguish new work from Pending/Retained. Pending and retained entries share MaxRetainedResults/MaxRetainedBytes. Pending survives retention sweeps until a terminal result or tombstone. Live terminal markers suppress dispatch (with duplicate-content validation against the retained digest); expired markers are replaced with Pending only after count and byte admission succeeds.
func (*ReliableManager) ReapExpired ¶
func (m *ReliableManager) ReapExpired(now time.Time) (outcomes, tombstones, resumes int, err error)
ReapExpired discards retained outcomes, tombstones, and resume handles past retention, returning per-kind counts. Expired outcomes leave a bounded Forgotten marker (bounded by MaxRetainedResults, independent from MaxTombstones); expired Forgotten markers beyond retention are dropped. Expired resume and revoked handles share the resume lifetime; both are reaped here and counted together in resumes. Live pending work is never reaped. Idle attachments are detached even if their signal cannot be queued; err reports the first queue failure while retention cleanup still completes.
func (*ReliableManager) Reconcile ¶
func (m *ReliableManager) Reconcile(now time.Time, sid SessionID, did DeliveryID) (ReconcileOutcome, *StoredOutcome, error)
Reconcile returns retained/forgotten/unknown/pending for a delivery ID. Unknown is returned only for never-seen IDs; expired outcomes and expired tombstones resolve to Forgotten via a bounded marker. Pending means dispatched but no terminal outcome yet: callers MUST resend the same delivery ID and wait, MUST NOT dispatch as new.
func (*ReliableManager) RecordResult ¶
func (m *ReliableManager) RecordResult(now time.Time, sid SessionID, epoch uint64, did DeliveryID, method string, payload []byte, outcome StoredOutcome) (ReconcileOutcome, error)
RecordResult retains a terminal outcome (duplicate-content checked). The caller passes the attachment epoch it holds; stale/zero/future epochs are rejected with FAILED_PRECONDITION before ANY mutation or activity refresh. NoteDispatch uses the same epoch fencing. Activity (lastActivity) is refreshed only when accepting a terminal result: new insert, expired-marker replacement, and idempotent live duplicate. Failed admission (epoch mismatch, content mismatch, budget exhaustion, unknown session) preserves markers, bytes, and activity.
func (*ReliableManager) RecordTombstone ¶
func (m *ReliableManager) RecordTombstone(now time.Time, sid SessionID, did DeliveryID, code ErrorCode) error
RecordTombstone records a terminal tombstone (deadline/cancel only; UNAVAILABLE is unknown-outcome and must never be tombstoned) for a delivery ID. The caller must establish that execution is terminal and can no longer produce effects; a cancellation request or elapsed deadline alone is insufficient to release live Pending work. First-write-wins: a live duplicate with the same code is idempotent (retainedAt untouched); a live duplicate with a different code is rejected without overwriting. Outcomes and tombstones are exclusive: tombstoning a delivery ID with a live retained outcome is rejected with FAILED_PRECONDITION and preserves the outcome. Expired-retained handling (explicit): an expired retained outcome is retired (bytes freed, digest propagated to a transient Forgotten marker) and the tombstone is then admitted as the new terminal; if tombstone admission fails (budget exhausted) the expired outcome is preserved (no mutation). The new tombstone retains the pending request digest when live pending work exists for the DID (common deadline/cancel path); otherwise it starts content-less and adopts the first live resend's digest in NoteDispatch.
func (*ReliableManager) Revoke ¶
Revoke withdraws one resume credential (rotation already revokes the predecessor; this covers explicit revocation).
func (*ReliableManager) Signal ¶
func (m *ReliableManager) Signal(sid SessionID, sig SessionSignal) error
Signal queues one lifecycle signal for a known session.
func (*ReliableManager) SweepIdle ¶
func (m *ReliableManager) SweepIdle(now time.Time) ([]SessionID, error)
SweepIdle enforces idle timeouts across sessions: actives past their lease IdleTimeoutMs are detached and an IdleTimeout signal is queued per session. It returns swept IDs and the first queue error, if any.
func (*ReliableManager) TombstoneOf ¶
func (m *ReliableManager) TombstoneOf(now time.Time, sid SessionID, did DeliveryID) (ErrorCode, bool, error)
TombstoneOf returns the tombstone code when present and unexpired.
type RequestBudget ¶
type RequestBudget struct {
// contains filtered or unexported fields
}
RequestBudget is a read-only SDK budget shared by authorization, handlers and terminal authority adapters. Its zero value is expired. Remaining also checks trusted suspend-inclusive elapsed time when the transport supports it; Deadline alone is a Go context deadline and may not account for machine suspension. Dispatch and terminal budgets also recheck retained ancestor clocks and cutoffs. Expiry cancels eligibility, not durable effects already admitted externally.
func RequestBudgetFromContext ¶
func RequestBudgetFromContext(ctx context.Context) (RequestBudget, bool)
RequestBudgetFromContext returns the SDK-selected budget, when called from Authorize, a handler, or a terminal authority callback. It grants no authority. Every terminal Commit/Observe callback, including driver refresh observations, gets a derived budget bounded by its operation/read cutoff and parent context. A child context may impose an earlier deadline; adapters must honor that too.
func (RequestBudget) Deadline ¶
func (b RequestBudget) Deadline() time.Time
Deadline returns the selected absolute Go deadline, including an earlier serving-context deadline. Terminal authority callbacks receive the narrower operation/read deadline. It never renews the allowance.
func (RequestBudget) Err ¶
func (b RequestBudget) Err() error
Err reports context.DeadlineExceeded once the SDK budget is exhausted or invalid. Callers must also honor their context's cancellation independently.
func (RequestBudget) Remaining ¶
func (b RequestBudget) Remaining() time.Duration
Remaining returns nonnegative time left under the original timing domains and all retained ancestor constraints, resampling each declared clock in its domain. Invalid continuity or duration arithmetic returns zero (fail closed).
type RequestBudgetFunc ¶
RequestBudgetFunc optionally selects a host cap for one validated request, before Authorize. Built-in recovery and already-expired or invalid original budgets skip this selector. The cap starts at complete-frame receipt, not at callback entry. False leaves the wire/default/MaxTimeout budget unchanged; true with zero expires immediately, and negative durations fail closed. A larger cap never extends an existing deadline. Implementations must be pure, prompt, bounded and concurrency-safe: no authorization, storage or network I/O. Payload is untrusted opaque borrowed data; do not mutate or retain it.
type RpcError ¶
type RpcError struct {
// Code is nonzero on emission; unknown received numbers map to
// ErrorCodeUnknown per SNTR-ERR-005.
Code ErrorCode
// Message is public failure text safe to return to the peer. It MUST
// NOT contain credentials, tokens, or private diagnostics
// (SNTR-ERR-003). Callers branch on Code, never on Message.
Message string
}
RpcError is the binding control error. It is returned as a Go error from validators, session machines, and transport pumps so callers can fail fast. Wire failures inside RpcResult use the generated syntrav1.RpcError; convert at the codec boundary with ToWire / RpcErrorFromWire.
func NewRpcError ¶
NewRpcError builds an *RpcError with code c and public message msg. It is fail-fast: an Unspecified code returns an Internal error carrying the caller message for triage, so an invalid emission can never escape as a success-shaped result.
func RpcErrorFromWire ¶
RpcErrorFromWire converts a wire failure to its control form, normalizing unknown codes to ErrorCodeUnknown.
func (*RpcError) Error ¶
Error implements the error interface for *RpcError. It prints the registry name plus the public message; the message is already public text, so this is safe to log.
type RpcRequest ¶
type RpcRequest = syntrav1.RpcRequest
RpcRequest carries opaque application data (rpc.proto).
type RpcResult ¶
RpcResult completes a call (rpc.proto).
func NewSuccessResult ¶
NewSuccessResult builds a payload RpcResult. Empty payload with a selected outcome means success, even for zero-byte results (SNTR-WIRE-007). A nil outcome is never success.
func NewWireErrorResult ¶
NewWireErrorResult builds an error RpcResult. An Unspecified code can never be emitted as a failure (SNTR-ERR-001), so it is mapped to Internal here rather than escaping as a success-shaped result.
type ServerReady ¶
type ServerReady = syntrav1.ServerReady
ServerReady confirms acceptance (handshake.proto).
type SessionID ¶
type SessionID [sessionIDLen]byte
SessionID is a 16-byte opaque session identity, distinct from connection_id.
func ValidateSessionID ¶
ValidateSessionID checks 16 non-zero bytes.
type SessionSignal ¶
type SessionSignal string
SessionSignal is a typed lifecycle signal (existing codes only).
const ( SignalDraining SessionSignal = "draining" SignalGoingAway SessionSignal = "going-away" SignalOverloaded SessionSignal = "overloaded" SignalFenced SessionSignal = "fenced" SignalExpired SessionSignal = "expired" SignalRevoked SessionSignal = "revoked" SignalIdleTimeout SessionSignal = "idle-timeout" )
func ParseSessionSignal ¶
func ParseSessionSignal(name string) (SessionSignal, error)
ParseSessionSignal parses a control-payload signal name (exact match).
type StagedSnapshot ¶
type StagedSnapshot struct {
// contains filtered or unexported fields
}
StagedSnapshot stages bounded snapshot pages under a provider-proven boundary. Pages are stored without interpretation and assembled only when every page 0..totalPages-1 has arrived exactly once.
func NewStagedSnapshot ¶
func NewStagedSnapshot(handle, boundary []byte, totalPages, pageMax int) (*StagedSnapshot, error)
NewStagedSnapshot begins staging totalPages pages under boundary. Bounds: 1 <= totalPages <= 256, 1 <= pageMax <= 262144.
func (*StagedSnapshot) Boundary ¶
func (s *StagedSnapshot) Boundary() []byte
Boundary returns the provider-proven boundary subsequent batches chain from.
func (*StagedSnapshot) Completion ¶
func (s *StagedSnapshot) Completion() (*pb.RecoverySnapshotComplete, error)
Completion is a local transfer record, never a wire notification or proof of persistence. It avoids assembling another copy merely to check completeness.
func (*StagedSnapshot) Install ¶
func (s *StagedSnapshot) Install() ([]byte, error)
Install assembles staged pages in order. It fails when any page is missing.
func (*StagedSnapshot) StageChunk ¶
func (s *StagedSnapshot) StageChunk(chunk *pb.RecoverySnapshotChunk) error
StageChunk checks the typed chunk's handle as well as its index and boundary.
type StoreError ¶
StoreError is a persistence failure. It never carries checkpoint bytes.
func (*StoreError) Error ¶
func (e *StoreError) Error() string
type StoredOutcome ¶
StoredOutcome is a retained terminal result (opaque payload or typed error).
type TerminalAuthority ¶
type TerminalAuthority interface {
// Commit conditionally records the application transition and exact ownership.
Commit(context.Context, TerminalTransition) error
// Observe returns fresh authority state, including any superseding denial.
Observe(context.Context, TerminalTransition) (TerminalObservation, error)
}
TerminalAuthority owns application persistence. Commit must atomically record ownership from the expected active revision and all fixed-receipt conditions. Observe must be a fresh, authoritative read covering expiry, key/enrollment and application authority, including superseding denial; caches/replicas unable to establish that are unsupported. Both methods must honor cancellation and return within the configured ObservationTimeout (Commit within its context budget). Every callback receives RequestBudgetFromContext timing derived to its actual operation/read cutoff, including periodic driver observations. Commit excludes the reserved teardown tail; Observe is additionally bounded by its read limit. Returning nil from Commit is never commit evidence. The SDK cannot prove an adapter's durability or make its transaction atomic with carrier I/O. A terminal callback may request Host.Close or Host.DisconnectPrincipal; the terminal connection's close join is retained rather than awaited on that callback's stack. Do not await Host.Wait/Done or the serving result inside a callback: joined cleanup necessarily includes the callback's own return.
type TerminalAuthorityState ¶
type TerminalAuthorityState uint8
TerminalAuthorityState classifies a fresh operation-aware authority read.
const ( // TerminalUnknown includes unresolved causes, stale reads, and missing state. TerminalUnknown TerminalAuthorityState = iota // TerminalActive means the exact expected authorization revision is active. TerminalActive // TerminalOwnedCommitted means this reservation owns the conditional commit. TerminalOwnedCommitted // TerminalDenied means external withdrawal, expiry, or superseding hard denial. TerminalDenied )
type TerminalChannelBinding ¶
type TerminalChannelBinding struct {
Identity ChannelIdentity
ServerKeyID uint32
HandshakeHash [32]byte
}
TerminalChannelBinding is confirmed transport evidence for the authority adapter. It is not a peer-supplied ID or a transferable receipt capability.
type TerminalClock ¶
type TerminalClock interface {
// Age returns trusted elapsed time from the channel's original origin.
Age() time.Duration
// Check rejects an invalidated or discontinuous origin.
Check() error
}
TerminalClock is a driver's trusted suspend-inclusive elapsed origin. Check must fail sticky on discontinuity; Age and Check must be prompt and safe concurrently. Unsupported drivers must not supply an untrusted wall clock.
type TerminalMethodPolicy ¶
type TerminalMethodPolicy struct {
SuccessPayload []byte
Authority TerminalAuthority
ObservationTimeout time.Duration
}
TerminalMethodPolicy explicitly enables one authorized method. SuccessPayload must be fixed, non-sensitive bytes; OpenHost copies it. The complete correlated Frame has an immutable 1024-byte ceiling. ObservationTimeout is a declared read bound, must be positive and at most one second, and never renews the total budget. Each read is bounded independently in both trusted elapsed and context time; exceeding it retires I/O even if the observer has not returned.
type TerminalObservation ¶
type TerminalObservation struct {
State TerminalAuthorityState
Transition TerminalTransition
Revision uint64
}
TerminalObservation is authoritative evidence, not callback success. Active requires Revision == ExpectedRevision. OwnedCommitted requires a strictly newer revision and an exact Transition match, including reservation and operation. The adapter must report later external denial even after an owned commit.
type TerminalPermit ¶
type TerminalPermit struct {
// contains filtered or unexported fields
}
TerminalPermit is an SDK-created, connection-private one-use permission. Its zero value grants nothing. Applications cannot create it through the handler API. Exported methods exist only for trusted driver integration, not policy or peer assertions; do not store permits across connections or expose them.
func (*TerminalPermit) CheckTime ¶
func (p *TerminalPermit) CheckTime() error
CheckTime enforces the original write budget in both elapsed and request time.
func (*TerminalPermit) Fail ¶
func (p *TerminalPermit) Fail(err error)
Fail installs an irreversible failure and synchronously cancels an admitted Commit's context before returning. It never joins carrier I/O. Late callback or read success cannot clear the failure or restore delivery eligibility.
func (*TerminalPermit) Frame ¶
func (p *TerminalPermit) Frame() []byte
Frame returns an owned copy of the sole predeclared result for the driver.
func (*TerminalPermit) Handoff ¶
func (p *TerminalPermit) Handoff() error
Handoff consumes the permit once after fresh driver validation. Concurrent locally observed denial serialized before this point wins. Remote denial after the last observation may race the first bytes; handed-off bytes cannot be recalled.
func (*TerminalPermit) MatchesChannel ¶
func (p *TerminalPermit) MatchesChannel(binding TerminalChannelBinding) bool
MatchesChannel checks exact authenticated enrollment scope for a trusted driver.
func (*TerminalPermit) Observe ¶
func (p *TerminalPermit) Observe(ctx context.Context, requireCommit bool) (TerminalAuthorityState, error)
Observe validates fresh typed evidence. Drivers serialize observations; no local mutex is held across authority I/O. Unknown/error/mismatch is sticky. Active never permits a receipt or ordinary traffic on the fenced connection. Once committed, a stale Active read cannot resurrect state. Every authority callback, including driver refresh, receives an SDK budget and context deadline clamped by the permit, this read's bound and the parent. Retained ancestor clocks are rechecked by the watchdog and after callback return; a valid-looking observation cannot repair an expired or discontinuous ancestor.
type TerminalReceiptDriver ¶
type TerminalReceiptDriver interface {
// TerminalClock returns this driver's original trusted clock.
TerminalClock() TerminalClock
// TerminalBinding returns current confirmed evidence for this exact channel.
TerminalBinding() (TerminalChannelBinding, bool)
// BeginTerminal joins the ordinary frame and identity-check barriers.
BeginTerminal(context.Context, *TerminalPermit) error
// ValidateTerminal classifies current authority; true requires owned commit.
ValidateTerminal(context.Context, *TerminalPermit, bool) error
// SendTerminal consumes one permit and attempts only its fixed ciphertext.
SendTerminal(context.Context, *TerminalPermit) error
// StopTerminal interrupts the carrier without joining the caller's operation.
StopTerminal()
}
TerminalReceiptDriver is the optional trusted ordered-driver contract. It is not a generic graceful-drain capability. BeginTerminal must establish the full frame boundary, install the shared authority classifier across ALL reader, writer and idle checks, and reject unsupported carriers before mutation. SendTerminal must freshly validate owned evidence and consume the exact permit at the serialized ciphertext handoff, repoll blocked I/O, and abort on any failure without replay. StopTerminal interrupts I/O without joining itself. Custom drivers must implement the whole contract or return no capability.
type TerminalReceiptProvider ¶
type TerminalReceiptProvider interface {
// TerminalReceiptDriver returns the exact coordinated owner, or nil.
TerminalReceiptDriver() TerminalReceiptDriver
}
TerminalReceiptProvider forwards the capability to the actual transport owner. Wrappers must preserve owner identity; nil means unsupported/default-disabled.
type TerminalTransition ¶
type TerminalTransition struct {
ReservationID [32]byte
Principal string
Channel ChannelIdentity
ServerKeyID uint32
HandshakeHash [32]byte
Method string
Operation string
ExpectedRevision uint64
}
TerminalTransition is private authority-adapter input, never wire data. The adapter must atomically compare ExpectedRevision and record the complete value with its application transition. ReservationID is fresh SDK randomness, not a diagnostic connection ID. Do not log, expose, or accept these fields from peers.
type Tracker ¶
type Tracker struct {
// contains filtered or unexported fields
}
Tracker correlates nonzero request IDs with exactly-one terminal results. It is safe for concurrent use by receive and timeout workers.
func NewTracker ¶
func NewTracker() *Tracker
NewTracker constructs an empty RPC correlation tracker.
func (*Tracker) Cancel ¶
Cancel marks requestID as cancelled best-effort: it returns true when the id is outstanding (the worker should observe IsCancelled and abandon work), false when unknown (already finished, expired, or never started). Cancel never deletes the call and never returns an error; a late Result after Cancel is still accepted because cancellation is advisory, never rollback (SNTR-RPC-005).
func (*Tracker) Expired ¶
Expired returns the ids whose deadlines are at or before now and removes them from the outstanding set. The caller fails each with a DeadlineExceeded result; removal here guarantees exactly-one terminal semantics (a late Finish for an expired id is ignored).
func (*Tracker) Finish ¶
Finish releases requestID after its terminal result. Unknown IDs are ignored. A nil result is InvalidArgument; callers that decode a result should pass the decoded value through ValidateResult first so a both/neither outcome is rejected before the table is touched.
func (*Tracker) FinishResult ¶
FinishResult completes requestID with exactly one terminal result: a both/neither outcome or an error result with an Unspecified code is InvalidArgument and the id stays outstanding; unknown IDs are ignored.
func (*Tracker) IsCancelled ¶
IsCancelled reports whether requestID is outstanding and marked cancelled. It returns false for unknown ids so workers can poll without branching on existence first.
func (*Tracker) Start ¶
Start registers requestID for method. It fails closed on zero IDs, duplicate IDs, uncanonical methods, and budget exhaustion. The call deadline is now plus DefaultRPCTimeout; use StartWithBudget for an explicit client budget.
func (*Tracker) StartWithBudget ¶
func (t *Tracker) StartWithBudget(now time.Time, requestID uint64, method string, timeoutMs uint32) error
StartWithBudget registers requestID for method with a timeout budget of timeoutMs (zero selects DefaultRPCTimeout). Budgets above MaxRPCTimeoutMs are clamped. now anchors the deadline; callers pass time.Now in production and a fixed clock in tests.
type Transport ¶
type Transport interface {
// Send transmits one serialized Frame. It MUST copy frame if it
// retains it and return promptly when ctx ends.
Send(ctx context.Context, frame []byte) error
// Recv returns the next inbound serialized Frame. It returns an
// error when the transport is closed and drained or ctx ends.
Recv(ctx context.Context) ([]byte, error)
// Close releases the transport and interrupts pending I/O. It is idempotent.
Close() error
}
Transport carries serialized Syntra Frames. Each Send transmits exactly one Frame toward the peer; each Recv returns exactly one inbound Frame. Implementations MUST preserve frame boundaries and MUST NOT batch multiple Frames into one Send payload. The session layer validates sizes and contents; transports MUST still bound allocation on receive.
func LoopbackPair ¶
func LoopbackPair() (a, b Transport)
LoopbackPair returns two connected in-memory Transports: frames sent on a arrive on b and vice versa. It is the standard harness for lifecycle tests and for embedding a session without a socket.
func WrapRecoveryTransport ¶
func WrapRecoveryTransport(t Transport, c *Client, inbox *RecoveryInbox) Transport
WrapRecoveryTransport is a compatibility adapter for an inbox already attached by NewRecoveryClient. Client.Run owns ordered validation and pre-queue routing; callers may pass their transport directly to Run.
type WireRpcError ¶
WireRpcError is the failure payload inside RpcResult (errors.proto).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package connection composes encrypted ordered-message carriers with Syntra sessions.
|
Package connection composes encrypted ordered-message carriers with Syntra sessions. |
|
gen
|
|
|
internal
|
|
|
elapsedctx
Package elapsedctx retains trusted SDK elapsed cutoffs behind scheduler timers.
|
Package elapsedctx retains trusted SDK elapsed cutoffs behind scheduler timers. |
|
File admission.go provides shared FIFO connection leases through joined cleanup.
|
File admission.go provides shared FIFO connection leases through joined cleanup. |
|
Package proxy negotiates explicit, bounded proxy tunnels on owned streams.
|
Package proxy negotiates explicit, bounded proxy tunnels on owned streams. |
|
Package routes composes explicitly provisioned connection paths.
|
Package routes composes explicitly provisioned connection paths. |
|
Package securechannel implements Syntra 1.0's integral encryption kernel.
|
Package securechannel implements Syntra 1.0's integral encryption kernel. |
|
transport
|
|
|
http
Package syntrahttp implements the explicitly selected Syntra HTTP/HTTPS carrier.
|
Package syntrahttp implements the explicitly selected Syntra HTTP/HTTPS carrier. |
|
ordered
File budget.go enforces ordered-driver establishment and elapsed operation bounds.
|
File budget.go enforces ordered-driver establishment and elapsed operation bounds. |
|
stream
Package stream gates connected application I/O during establishment.
|
Package stream gates connected application I/O during establishment. |
|
tcp
Package tcp carries encrypted Syntra records on an owned connected stream.
|
Package tcp carries encrypted Syntra records on an owned connected stream. |
|
tlsstream
Package tlsstream owns authenticated TLS on application-provided connections.
|
Package tlsstream owns authenticated TLS on application-provided connections. |
|
websocket
Package websocket carries one encrypted Syntra record per binary message.
|
Package websocket carries one encrypted Syntra record per binary message. |