syntra

package module
v1.0.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 18 Imported by: ? modules, 0 packages

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

README

Syntra Go

Syntra Go is a pure-Go SDK for Syntra 1.0 (syntra.1.0). It provides a core and socket-free session runtime, encrypted connections, credential-based session admission, concurrent RPCs, notifications, and optional typed update recovery. Import network, routes, proxy, and the carrier packages to add managed networking. The networking layer uses ordinary Go goroutines and Go's netpoll support; it does not create its own reactor or scheduler runtime.

Noise encryption is integral to Syntra 1.0. The generated protobuf Frame is the internal envelope carried inside encrypted records. Encoding a Frame alone does not establish a Syntra connection or define a plaintext protocol.

Applications can supply ordered record I/O or use the built-in carriers and managed clients/listeners. Trusted key provisioning, credential verification, per-method authorization, identity, and persistence belong to the application.

Install

go get github.com/tinkle-org/syntra-go

The module requires Go 1.23.0 or later. CI uses Go 1.26.10 for current checks and Go 1.23.12 for compatibility. Build deployed applications with a security-patched toolchain. The compatibility floor is not a runtime security recommendation.

Make a call

This helper takes an application callback that establishes ordered.MessageIO, a provisioned encryption configuration, and an explicit hello credential. One budget covers carrier setup, encryption, authentication and readiness. The peer must serve /example.Echo/Echo and authorize that method. connection.Connect owns the supplied I/O and returns a ready client; the helper makes one call and closes the client.

package example

import (
	"context"
	"time"

	syntra "github.com/tinkle-org/syntra-go"
	"github.com/tinkle-org/syntra-go/connection"
	"github.com/tinkle-org/syntra-go/securechannel"
	"github.com/tinkle-org/syntra-go/transport/ordered"
)

func Echo(ctx context.Context, setup func(context.Context) (ordered.MessageIO, error),
	encryption securechannel.ClientConfig, credential []byte,
) ([]byte, error) {
	budget, err := ordered.NewEstablishmentBudget(nil, 15*time.Second)
	if err != nil {
		return nil, err
	}
	establish, cancel := budget.Context(ctx)
	defer cancel()

	records, err := setup(establish)
	if err != nil {
		return nil, err
	}
	client, err := connection.Connect(establish, records, encryption,
		syntra.ClientConfig{Credential: credential}, ordered.Options{Budget: budget})
	if err != nil {
		return nil, err
	}
	defer client.Close()
	return client.Call(ctx, "/example.Echo/Echo", []byte("hello"), 1000)
}

The final argument to Call is the requested timeout in milliseconds. Zero selects the configured default. Cancellation and timeouts do not roll back application effects or establish that retrying is safe.

See CONNECTION.md for the I/O contract, host setup, readiness, ownership, and limits.

Packages and session APIs

  • network.New(network.DefaultConfig()) creates a bounded owner for managed clients and listeners. Network.Client supervises reconnects; ListenTCP, ListenWS, ListenWSS, ListenHTTP, and ListenHTTPS own listeners, admission, sessions, and teardown.
  • routes builds allowlisted, one-endpoint-per-attempt connectors with fresh security inputs. proxy provides explicit bounded tunnels and hop credentials.
  • transport/tcp, transport/websocket, and transport/http implement carriers; transport/tlsstream wraps owned streams using application TLS or its StandardProvider. transport/stream supplies shared stream I/O gates.
  • connection composes encryption and session readiness with Connect and Accept. NewServer optionally owns a host and bounds admitted connections.
  • The root syntra package contains frame validation and codecs, OpenClient, Client.Run, Client.WaitReady, Client.Call, OpenHost, and Host.Serve.
  • securechannel implements the protocol's Noise handshake, identity evidence, encrypted records, and bounded frame assembly.
  • transport/ordered connects that encryption to application-owned MessageIO and exposes a frame-level syntra.Transport to sessions.
  • gen/syntra/v1 contains generated protobuf messages for internal envelopes and typed recovery payloads.

The root and securechannel dependency graphs exclude the optional networking packages. The standard carrier codes are TCP 1, WS 2 (loopback only), and WSS 3. HTTP 4 and HTTPS 5 are explicit candidates: both peers must set AllowHTTPCandidate on their own security configuration. Default validation, parsing, encoding, and handshakes reject those candidates. Cross-carrier route selection requires an explicit policy and excludes WS. See managed networking for setup and ownership.

HostConfig.ChannelPolicy verifies confirmed channel evidence and the explicit hello credential, returning the principal to bind to the session. When it is configured, it replaces HostConfig.Policy. A channel principal does not automatically authenticate the hello credential. Missing credential policy denies admission; missing HostConfig.Authorize denies every method.

HostConfig.Authorize runs for every method before handler effects. Handlers receive a context bounded by the call budget and must stop and join their own work when it ends. Return NewSuccessResult for success or a typed RpcError with safe public text for a method failure.

Host.NotifyDirected targets all connections of a principal. Host.NotifyAll broadcasts to active connections. Successful enqueue is not a delivery acknowledgement. Running clients receive live updates automatically through Notifications() even when no RPC is issued. Ordinary notifications use a bounded, lossy queue; LossTotals and WaitLossChange expose loss observations. Managed clients continuously drain that queue and expose generation-bound NextNotification(ctx), with dropped-count and dropped-byte totals. Those generation-local counters are not durable recovery checkpoints.

Optional update recovery

Recovery uses typed RPC and notification payloads within the same encrypted protocol. Set HostConfig.Recovery to a RecoveryService; the runtime opens and manages a recovery session for each authenticated connection. On the client, NewRecoveryClient attaches one immutable inbox before Client.Run. With connection.Connect, construct it in ClientConfig.Prepare. After readiness, explicitly negotiate syntra.update-recovery/1 to enable recovery traffic. Managed clients use a configured recovery factory and pre-Run preparer to attach and negotiate a fresh recovery profile for every connection generation; CoreReady and RecoveryNegotiated are separate states.

The APIs cover subscriptions, replay, catch-up, confirmation, snapshot transfer, and unsubscribe. RecoveryInbox routes recovery traffic before the ordinary lossy notification queue. Host sessions bind handles to one authenticated connection and recheck stream authorization and generation. See CONNECTION.md for setup and lifecycle.

The application implements RecoverySource for stream history, issued-checkpoint validation, publication ordering, and immutable snapshots. It implements RecoveryPersistence to commit the full opaque application state with its position. PersistenceScope contains the principal namespace and stable stream; DurableRecord contains generation G, checkpoint, and full application state. Commit compares the expected generation/checkpoint and updates the whole record atomically. A nil expected position requires absence; an exact full-record duplicate is a no-op.

Persist a batch or complete snapshot before confirming it. RecoveryProgress keeps locally durable, confirm-sent, and peer-acknowledged positions separate. CommitUnknown requires reload and reconciliation on a fresh connection. The bounded MemoryRecoveryStore is volatile. Recovery does not provide exactly-once application effects or make arbitrary RPC replay safe. The SDK treats application state and payloads as opaque bytes and imports no application-domain schemas.

Development

CGO_ENABLED=0 go build -mod=readonly ./...
CGO_ENABLED=0 go test -mod=readonly -count=1 ./...
go vet -mod=readonly ./...
go test -mod=readonly -race -count=1 ./...
go test -mod=readonly -race -count=1 ./network ./routes ./proxy ./transport/...

Generation uses Buf 1.59.0 and the Go protobuf plugin v1.36.6 revision 1. The protobuf runtime is v1.36.6. Generated output is committed under gen/.

buf generate --template buf.gen.yaml
python3 scripts/check-go-package.py
python3 scripts/check-generated.py

CI checks Buf FILE compatibility except FILE_SAME_GO_PACKAGE; the local package check enforces canonical go_package options in compiled descriptors. The required network integration lane uses real loopback sockets without Docker, checks structured test execution, and runs alongside dependency-isolation and default candidate-rejection checks.

Read CONTRIBUTING.md for checks, BENCHMARKS.md for measurement boundaries, SECURITY.md for security responsibilities and private reports, and AUDIT.md for verification scope and evidence limits.

Documentation

Overview

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.

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.

Index

Constants

View Source
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
)
View Source
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
)
View Source
const MaxRPCTimeoutMs uint32 = 120_000

MaxRPCTimeoutMs is the default maximum call budget. Sessions clamp larger requests to their configured maximum.

View Source
const ReliableSessionCapability = "syntra.reliable-session/1"

ReliableSessionCapability is the optional capability identifier.

Variables

View Source
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.

View Source
var ErrRecoveryRetentionMiss = errors.New("syntra: recovery retention unavailable")

ErrRecoveryRetentionMiss requests snapshot fallback without changing continuity.

View Source
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

func AllowAllAuthorize(ctx context.Context, principal string, method string) error

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

func CheckEpochAdvance(current, proposed uint64) error

CheckEpochAdvance enforces monotonic fencing (proposed > current).

func DecodeRecovery

func DecodeRecovery(data []byte, m proto.Message) error

DecodeRecovery bounds fields before allocation and ignores well-formed unknown fields. Ordinary protobuf merge and last-value semantics apply inside profile messages.

func DenyAllAuthorize

func DenyAllAuthorize(ctx context.Context, principal string, method string) error

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 EncodeRecovery

func EncodeRecovery(m proto.Message) ([]byte, error)

func ErrorCodeName

func ErrorCodeName(c ErrorCode) string

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 IsAborted

func IsAborted(c ErrorCode) bool

IsAborted reports whether c is Aborted.

func IsAlreadyExists

func IsAlreadyExists(c ErrorCode) bool

IsAlreadyExists reports whether c is AlreadyExists.

func IsAuthFailure

func IsAuthFailure(c ErrorCode) bool

IsAuthFailure reports whether c denies the caller (Unauthenticated or PermissionDenied).

func IsCancelled

func IsCancelled(c ErrorCode) bool

IsCancelled reports whether c is Cancelled.

func IsClientError

func IsClientError(c ErrorCode) bool

IsClientError reports whether c is the caller's fault. These never trip breakers or alerts.

func IsDataLoss

func IsDataLoss(c ErrorCode) bool

IsDataLoss reports whether c is DataLoss.

func IsDeadlineExceeded

func IsDeadlineExceeded(c ErrorCode) bool

IsDeadlineExceeded reports whether c is DeadlineExceeded.

func IsFailedPrecondition

func IsFailedPrecondition(c ErrorCode) bool

IsFailedPrecondition reports whether c is FailedPrecondition.

func IsInternal

func IsInternal(c ErrorCode) bool

IsInternal reports whether c is Internal.

func IsInvalidArgument

func IsInvalidArgument(c ErrorCode) bool

IsInvalidArgument reports whether c is InvalidArgument.

func IsNotFound

func IsNotFound(c ErrorCode) bool

IsNotFound reports whether c is NotFound.

func IsOutOfRange

func IsOutOfRange(c ErrorCode) bool

IsOutOfRange reports whether c is OutOfRange.

func IsPermissionDenied

func IsPermissionDenied(c ErrorCode) bool

IsPermissionDenied reports whether c is PermissionDenied.

func IsRecoveryMethod

func IsRecoveryMethod(method string) bool

func IsReservedFieldName

func IsReservedFieldName(name string) bool

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

func IsReservedFieldNumber(n int) bool

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

func IsResourceExhausted(c ErrorCode) bool

IsResourceExhausted reports whether c is ResourceExhausted.

func IsRetryable

func IsRetryable(c ErrorCode) bool

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

func IsServerError(c ErrorCode) bool

IsServerError reports whether c is the host's fault. These feed breaker and alerting policy.

func IsUnauthenticated

func IsUnauthenticated(c ErrorCode) bool

IsUnauthenticated reports whether c is Unauthenticated.

func IsUnavailable

func IsUnavailable(c ErrorCode) bool

IsUnavailable reports whether c is Unavailable.

func IsUnimplemented

func IsUnimplemented(c ErrorCode) bool

IsUnimplemented reports whether c is Unimplemented.

func IsUnknown

func IsUnknown(c ErrorCode) bool

IsUnknown reports whether c is Unknown (including out-of-range numbers).

func IsValidFailure

func IsValidFailure(c ErrorCode) bool

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

func MarshalFrame(f *Frame) ([]byte, error)

MarshalFrame encodes f to protobuf binary wire bytes. It validates both the frame value and the emitted wire, including retained unknown fields.

func NegotiateVersion

func NegotiateVersion(min, max uint32) (uint32, error)

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

func NegotiateVersionRanges(clientMin, clientMax, serverMin, serverMax uint32) (uint32, error)

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

func NewConnectionID() (string, error)

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 NextEpoch

func NextEpoch(current uint64) (uint64, error)

NextEpoch advances the fencing epoch (u64::MAX is terminal).

func ValidateBodyCardinality

func ValidateBodyCardinality(f *Frame) error

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

func ValidateCredentialSize(credential []byte) error

ValidateCredentialSize rejects oversized credentials before any verifier runs. Empty credentials are an authentication attempt subject to host policy, not a parse error.

func ValidateEpoch

func ValidateEpoch(epoch uint64) error

ValidateEpoch checks nonzero.

func ValidateFrame

func ValidateFrame(f *Frame) error

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

func ValidateFrameSize(n int) error

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

func ValidateMethod(method string) error

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

func ValidatePayloadSize(n int) error

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

func ValidateRecovery(m proto.Message) error

ValidateRecovery validates defined fields; unknown protobuf fields confer no authority.

func ValidateRequestID

func ValidateRequestID(f *Frame) error

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

func ValidateResult(r *RpcResult) error

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

func ValidateResumeCredential(cred []byte) ([]byte, error)

ValidateResumeCredential checks opaque handle bounds (16..256, 32-byte v1).

func ValidateVersion

func ValidateVersion(v uint32) error

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

type AuthorizeFunc func(ctx context.Context, principal string, method string) error

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

func BodyKindOf(f *Frame) BodyKind

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 Cancel

type Cancel = syntrav1.Cancel

Cancel is an advisory cancellation target (rpc.proto).

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

type ChannelPolicy func(context.Context, ChannelIdentity, []byte) (string, error)

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

func (c *Client) Close() error

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

func (c *Client) DroppedBytes() uint64

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

func (c *Client) DroppedNotifications() uint64

DroppedNotifications reports notifications discarded under overflow.

func (*Client) IsClosed

func (c *Client) IsClosed() bool

IsClosed reports the session's admission fence without waiting for teardown.

func (*Client) LossTotals

func (c *Client) LossTotals() (dropped uint64, droppedBytes uint64)

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

func (c *Client) Run(ctx context.Context, t Transport) (runErr error)

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

func (c *Client) TerminalError() error

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

func (c *Client) WaitReady(ctx context.Context) error

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

type CommittedPosition struct {
	Stream     string
	Generation uint64
	Committed  []byte
}

CommittedPosition is the last confirmed position for one stream.

type ConfirmedLease

type ConfirmedLease struct {
	IdleTimeoutMs       uint32
	KeepaliveIntervalMs uint32
}

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

type CredentialPolicy func(ctx context.Context, credential []byte) (principal string, err error)

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

type DurableRecord struct {
	Generation                   uint64
	Checkpoint, ApplicationState []byte
}

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

type ErrorCode = syntrav1.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 indicates unavailability; effects may be unknown.
	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

func NormalizeErrorCode(n int32) ErrorCode

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

type ExpectedPosition struct {
	Generation uint64
	Checkpoint []byte
}

func (ExpectedPosition) GoString

func (r ExpectedPosition) GoString() string

func (ExpectedPosition) String

func (r ExpectedPosition) String() string

type Frame

type Frame = syntrav1.Frame

Frame is the versioned Syntra envelope (envelope.proto).

func NewCancelFrame

func NewCancelFrame(version uint32, requestID uint64) *Frame

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

func NewResultFrame(version uint32, requestID uint64, res *RpcResult) *Frame

NewResultFrame builds a result Frame with nonzero correlation.

func UnmarshalFrame

func UnmarshalFrame(data []byte) (*Frame, error)

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 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

func (h *Host) Close() error

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.

func (*Host) DisconnectPrincipal

func (h *Host) DisconnectPrincipal(principal string) error

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.

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

func (h *Host) NotifyAll(payload []byte) error

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

func (h *Host) NotifyDirected(principal string, payload []byte) error

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

func (h *Host) Serve(ctx context.Context, t Transport) (serveErr error)

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.

func (*Host) Wait

func (h *Host) Wait(ctx context.Context) error

Wait joins shutdown ownership. Canceling ctx stops only this wait.

type HostConfig

type HostConfig struct {
	// 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
	// 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

type LeaseProposal struct {
	IdleTimeoutMs       uint32
	KeepaliveIntervalMs uint32
}

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 (*MemoryRecoveryStore) FailNextCommit

func (s *MemoryRecoveryStore) FailNextCommit()

func (*MemoryRecoveryStore) Load

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 NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty store.

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 (
	PersistenceUnavailable PersistenceError = iota + 1
	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 (*RecoveryClient) Close

func (c *RecoveryClient) Close()

func (*RecoveryClient) Confirm

func (*RecoveryClient) Inbox

func (c *RecoveryClient) Inbox() *RecoveryInbox

func (*RecoveryClient) Negotiate

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 (*RecoveryClient) SnapshotBytes

func (c *RecoveryClient) SnapshotBytes(ctx context.Context, handle []byte) ([]byte, error)

SnapshotBytes returns the complete opaque transfer for application installation.

func (*RecoveryClient) SnapshotConfirm

func (*RecoveryClient) SnapshotFetch

func (*RecoveryClient) SnapshotOffer

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

type RecoveryConnection

type RecoveryConnection struct {
	ID, Principal string
	Version       uint32
}

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

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 RecoveryProviderSnapshot

type RecoveryProviderSnapshot struct {
	Key, Boundary    []byte
	Pages, PageBytes int
}

type RecoveryProviderStream

type RecoveryProviderStream struct {
	Identity   []byte
	Generation uint64
	Boundary   []byte
}

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

type RecoverySource

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 RecoveryStoredBatch struct {
	Generation                   uint64
	Predecessor, Result, Payload []byte
}

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

func (m *ReliableManager) CheckIdle(now time.Time, sid SessionID) (bool, error)

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

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

func (m *ReliableManager) Revoke(now time.Time, cred []byte) (bool, error)

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 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

func NewRpcError(c ErrorCode, msg string) *RpcError

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

func RpcErrorFromWire(w *syntrav1.RpcError) *RpcError

RpcErrorFromWire converts a wire failure to its control form, normalizing unknown codes to ErrorCodeUnknown.

func (*RpcError) Error

func (e *RpcError) Error() string

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.

func (*RpcError) ToWire

func (e *RpcError) ToWire() *syntrav1.RpcError

ToWire converts a control error to its wire form.

func (*RpcError) Unwrap

func (e *RpcError) Unwrap() error

Unwrap returns nil: RpcError is a leaf value, not a wrapper.

type RpcRequest

type RpcRequest = syntrav1.RpcRequest

RpcRequest carries opaque application data (rpc.proto).

type RpcResult

type RpcResult = syntrav1.RpcResult

RpcResult completes a call (rpc.proto).

func NewSuccessResult

func NewSuccessResult(payload []byte) *RpcResult

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

func NewWireErrorResult(code ErrorCode, msg string) *RpcResult

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

func ValidateSessionID(id []byte) (SessionID, error)

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.

func (*StagedSnapshot) StagePage

func (s *StagedSnapshot) StagePage(index int, bytes, boundary []byte) error

StagePage stores one page. Out-of-range indexes, oversized pages, and boundary mismatches fail. Re-staging identical bytes is idempotent; different bytes for the same index fail.

type StoreError

type StoreError struct {
	Code    ErrorCode
	Message string
}

StoreError is a persistence failure. It never carries checkpoint bytes.

func (*StoreError) Error

func (e *StoreError) Error() string

type StoredOutcome

type StoredOutcome struct {
	Payload []byte
	Err     *RpcError
}

StoredOutcome is a retained terminal result (opaque payload or typed error).

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

func (t *Tracker) Cancel(requestID uint64) bool

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

func (t *Tracker) Expired(now time.Time) []uint64

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

func (t *Tracker) Finish(requestID uint64) error

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

func (t *Tracker) FinishResult(requestID uint64, result *RpcResult) error

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

func (t *Tracker) IsCancelled(requestID uint64) bool

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) Pending

func (t *Tracker) Pending() int

Pending returns the count of in-flight RPCs for backpressure triage.

func (*Tracker) Start

func (t *Tracker) Start(requestID uint64, method string) error

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

type WireRpcError = syntrav1.RpcError

WireRpcError is the failure payload inside RpcResult (errors.proto).

Directories

Path Synopsis
Package connection composes encrypted ordered-message carriers with Syntra sessions.
Package connection composes encrypted ordered-message carriers with Syntra sessions.
gen
Package network owns bounded reconnecting clients and network services.
Package network owns bounded reconnecting clients and network services.
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
Package ordered binds Syntra records to an ordered, message-oriented carrier.
Package ordered binds Syntra records to an ordered, message-oriented carrier.
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.

Jump to

Keyboard shortcuts

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