Documentation
¶
Overview ¶
Package kanarpc implements context-first unary and server-streaming RPC. The v2 experimental protocol is intentionally incompatible with KanaRPC-Go.
Index ¶
- Constants
- Variables
- func CaptureTrailers(ctx context.Context, capture *MetadataCapture) context.Context
- func DrainReceiver(s Receiver) error
- func RegisterHealth(s *Server) error
- func RegisterIntrospection(s *Server) error
- func RegisterProtobufMethods(s *Server, bindings ...ProtobufMethod) error
- func RegisterProtobufStream[Request, Response proto.Message](s *Server, path string, newRequest func() Request, ...) error
- func RegisterProtobufUnary[Request, Response proto.Message](s *Server, path string, newRequest func() Request, ...) error
- func RegisterStream[Request, Response any](s *Server, path string, ...) error
- func RegisterUnary[Request, Response any](s *Server, path string, h func(context.Context, Request) (Response, error)) error
- func SetTrailer(ctx context.Context, metadata Metadata) error
- func WithOutgoingMetadata(ctx context.Context, m Metadata) context.Context
- type AdmissionStats
- type Authenticator
- type BudgetError
- type BufferStats
- type BufferUsage
- type ByteStats
- type CallInfo
- type CallResult
- type Caller
- type Capabilities
- type CapabilityError
- type Client
- func (c *Client) AdmissionStats() AdmissionStats
- func (c *Client) BufferStats() BufferStats
- func (c *Client) Call(ctx context.Context, method string, request, response any) error
- func (c *Client) Capabilities() Capabilities
- func (c *Client) Close()
- func (c *Client) CompressionStats() CompressionStats
- func (c *Client) FeedbackStats() FeedbackStats
- func (c *Client) MemoryStats() MemoryStats
- func (c *Client) OpenStream(ctx context.Context, method string, request any) (Receiver, error)
- func (c *Client) Stats() ClientStats
- func (c *Client) Stream(ctx context.Context, method string, request any) (*Stream, error)
- func (c *Client) WaitIdle(ctx context.Context) error
- type ClientConfig
- type ClientPipeline
- func (p *ClientPipeline) AdmissionStats() AdmissionStats
- func (p *ClientPipeline) Call(ctx context.Context, method string, request, response any) (err error)
- func (p *ClientPipeline) Close()
- func (p *ClientPipeline) OpenStream(ctx context.Context, method string, request any) (result Receiver, err error)
- func (p *ClientPipeline) Wait(ctx context.Context) error
- type ClientStats
- type Code
- type Completion
- type CompressionConfig
- type CompressionStats
- type ControlDecision
- type ControlMode
- type DeliveryFaults
- type DialOptions
- type DrainReport
- type Endpoint
- type Feature
- type FeedbackConfig
- type FeedbackMethod
- type FeedbackStats
- type GovernanceConfig
- type GovernanceSnapshot
- type HealthStatus
- type IOConfig
- type Identity
- type Interceptor
- type MemoryAccount
- type MemoryAccountStats
- type MemoryConfig
- type MemoryGroupStats
- type MemoryPool
- type MemoryPoolConfig
- type MemoryPoolStats
- type MemoryStats
- type MemoryUsage
- type Metadata
- type MetadataCapture
- type MethodInfo
- type MethodPolicy
- type MethodState
- type Metrics
- type Peer
- type PipelineConfig
- type Pressure
- type ProtobufMethod
- type ProtobufRequest
- type QUICClient
- func (c *QUICClient) AdmissionStats() AdmissionStats
- func (c *QUICClient) BufferStats() BufferStats
- func (c *QUICClient) Call(ctx context.Context, method string, request, response any) error
- func (c *QUICClient) Capabilities() Capabilities
- func (c *QUICClient) Close()
- func (c *QUICClient) CompressionStats() CompressionStats
- func (c *QUICClient) FeedbackStats() FeedbackStats
- func (c *QUICClient) MemoryStats() MemoryStats
- func (c *QUICClient) OpenStream(ctx context.Context, method string, request any) (Receiver, error)
- func (c *QUICClient) Stats() QUICStats
- func (c *QUICClient) Stream(ctx context.Context, method string, request any) (*Stream, error)
- func (c *QUICClient) WaitIdle(ctx context.Context) error
- type QUICConfig
- type QUICListener
- type QUICStats
- type QueuePolicy
- type RateLimitError
- type RateLimiter
- type RateSpec
- type RateStats
- type Receiver
- type RetryPolicy
- type Sender
- type Server
- func (s *Server) Close()
- func (s *Server) CompressionStats() CompressionStats
- func (s *Server) Drain(ctx context.Context) error
- func (s *Server) DrainWithReport(ctx context.Context) (report DrainReport, err error)
- func (s *Server) Governance() GovernanceSnapshot
- func (s *Server) HandleStream(path string, h StreamHandler) error
- func (s *Server) HandleUnary(path string, h UnaryHandler) error
- func (s *Server) Health() HealthStatus
- func (s *Server) HealthHandler() http.Handler
- func (s *Server) MemoryStats() MemoryStats
- func (s *Server) Methods() []MethodInfo
- func (s *Server) Ready() bool
- func (s *Server) ResetAdaptive(path string) error
- func (s *Server) Serve(listener net.Listener) error
- func (s *Server) ServeQUIC(listener *QUICListener) error
- func (s *Server) ServeTLS(listener net.Listener, options TLSOptions) error
- func (s *Server) SetServing(serving bool)
- func (s *Server) Stats() ServerStats
- func (s *Server) Wait(ctx context.Context) error
- type ServerConfig
- type ServerOutcomes
- type ServerStats
- type ServiceCaller
- type Status
- type Stream
- type StreamHandler
- type TCPKeepAliveConfig
- type TLSOptions
- type TraceConfig
- type TraceEvent
- type TraceRecorder
- type TraceRef
- type TraceSnapshot
- type Transport
- type UnaryHandler
Examples ¶
Constants ¶
const MaxMetadataBytes = 4096
const SupportPackageIsVersion1 = true
SupportPackageIsVersion1 is the compile-time contract required by generated bindings. Supported generation APIs remain available across compatible SDKs.
Variables ¶
var ( ErrClosed = errors.New("kanarpc: closed") ErrDraining = errors.New("kanarpc: draining") ErrProtocol = errors.New("kanarpc: peer violated protocol") ErrDelivery = errors.New("kanarpc: terminal receipt not acknowledged") )
var ErrCapabilities = errors.New("kanarpc: required protocol capabilities unavailable")
Functions ¶
func CaptureTrailers ¶
func CaptureTrailers(ctx context.Context, capture *MetadataCapture) context.Context
func DrainReceiver ¶
DrainReceiver consumes a stream to its protocol terminal without decoding.
func RegisterHealth ¶
RegisterHealth exposes JSON health Check/Watch over the same authenticated transport and optional authentication policy. State is application-controlled.
func RegisterIntrospection ¶
RegisterIntrospection is opt-in and uses the same authentication middleware. It publishes method names/shapes, not a gRPC reflection service.
func RegisterProtobufMethods ¶
func RegisterProtobufMethods(s *Server, bindings ...ProtobufMethod) error
RegisterProtobufMethods installs a service atomically before Serve. Invalid or duplicate bindings leave the server unchanged.
func RegisterProtobufStream ¶
func RegisterProtobufUnary ¶
func RegisterStream ¶
Types ¶
type AdmissionStats ¶
type AdmissionStats struct {
Limit, Active, Preparing, Encoding, Peak int
EncodingWaiters int
Rejected uint64
Closed bool
}
AdmissionStats includes accepted preparation, wire calls and owned cleanup. Finished unread stream buffers are accounted separately by MemoryStats.
type Authenticator ¶
Authenticator validates credentials from IncomingMetadata. It executes in the bounded request worker, before decompression and application decoding.
type BudgetError ¶
type BudgetError struct {
Class, Scope string
Requested, Used, Limit int64
// contains filtered or unexported fields
}
BudgetError identifies a local framework reservation refusal. Across the wire only Status is transmitted: a remote ResourceExhausted or reset does not establish which budget (or whether a budget) refused the peer. Scope is owner, pool_class, pool_data, or closed_owner. Used is the usage used for this decision (zero for an impossible absolute-size reservation).
func (*BudgetError) Error ¶
func (e *BudgetError) Error() string
func (*BudgetError) Unwrap ¶
func (e *BudgetError) Unwrap() error
type BufferStats ¶
type BufferUsage ¶
type Caller ¶
type Caller interface {
Call(context.Context, string, any, any) error
Stream(context.Context, string, any) (*Stream, error)
Close()
}
func DialEndpoint ¶
type Capabilities ¶
type CapabilityError ¶
CapabilityError precedes business dispatch. It never authorizes a retry of another call. Cause preserves cancellation, deadlines and handshake failures.
func (*CapabilityError) Error ¶
func (e *CapabilityError) Error() string
func (*CapabilityError) Unwrap ¶
func (e *CapabilityError) Unwrap() error
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client owns a single multiplexed byte-stream connection. There is no implicit reconnect, business retry, registry worker, or background heartbeat.
func DialTLS ¶
func DialTLS(ctx context.Context, address string, options TLSOptions, cfg ClientConfig) (*Client, error)
func NewClient ¶
func NewClient(conn net.Conn, cfg ClientConfig) (*Client, error)
NewClient transfers conn ownership on success only. It also accepts a caller-authenticated TLS connection; TLS construction is not automated here. RequiredFeatures performs bounded network IO before returning. On failure the caller still owns conn and must close it; negotiation may have written.
func (*Client) AdmissionStats ¶
func (c *Client) AdmissionStats() AdmissionStats
func (*Client) BufferStats ¶
func (c *Client) BufferStats() BufferStats
func (*Client) Capabilities ¶
func (c *Client) Capabilities() Capabilities
func (*Client) CompressionStats ¶
func (c *Client) CompressionStats() CompressionStats
func (*Client) FeedbackStats ¶
func (c *Client) FeedbackStats() FeedbackStats
func (*Client) MemoryStats ¶
func (c *Client) MemoryStats() MemoryStats
func (*Client) OpenStream ¶
func (*Client) Stats ¶
func (c *Client) Stats() ClientStats
func (*Client) Stream ¶
Stream begins one server-streaming call. Caller cancellation is always sent on the wire. Call and Stream share the same request/terminal state machine.
type ClientConfig ¶
type ClientConfig struct {
EnableCallOptions bool
Compression *CompressionConfig
TCPKeepAlive *TCPKeepAliveConfig
// RequiredFeatures enables a bounded pre-dispatch handshake. Zero preserves
// legacy JSON connections. Protobuf calls require FeatureProtobuf here.
RequiredFeatures Feature
// MemoryAccount is an optional single-owner share of a MemoryPool.
MemoryAccount *MemoryAccount
Feedback *FeedbackConfig
Memory MemoryConfig
IO IOConfig
Timeout time.Duration
MaxInFlight int
StreamWindow int
ControlTimeout time.Duration
// contains filtered or unexported fields
}
type ClientPipeline ¶
type ClientPipeline struct {
// contains filtered or unexported fields
}
ClientPipeline is the single production call entry for direct clients and routing.Client alike; generated SDKs consume this same ServiceCaller.
func NewClientPipeline ¶
func NewClientPipeline(inner ServiceCaller, cfg PipelineConfig) (*ClientPipeline, error)
func (*ClientPipeline) AdmissionStats ¶
func (p *ClientPipeline) AdmissionStats() AdmissionStats
func (*ClientPipeline) Close ¶
func (p *ClientPipeline) Close()
func (*ClientPipeline) OpenStream ¶
type ClientStats ¶
type Code ¶
type Code string
const ( OK Code = "ok" Canceled Code = "canceled" DeadlineExceeded Code = "deadline_exceeded" ResourceExhausted Code = "resource_exhausted" InvalidArgument Code = "invalid_argument" Internal Code = "internal" NotFound Code = "not_found" Unauthenticated Code = "unauthenticated" PermissionDenied Code = "permission_denied" FailedPrecondition Code = "failed_precondition" )
func StatusCode ¶
StatusCode returns the sanitized framework classification for instrumentation.
type Completion ¶
type Completion interface {
Done() <-chan struct{}
Outcome() error
}
Completion exposes protocol termination separately from unread buffer ownership.
type CompressionConfig ¶
type CompressionConfig struct{ MinBytes int }
CompressionConfig enables gzip negotiation. Small/unprofitable messages stay plain. Workspace reservations are additional to payload reservations.
type CompressionStats ¶
type CompressionStats struct{ Prepared, GzipPrepared, PlainBytes, EncodedBodyBytes, DecodedGzip, InflatedBytes uint64 }
CompressionStats measures prepared business bodies, not successful delivery, TCP/TLS/QUIC overhead, or application consumption. Counters are cumulative.
type ControlDecision ¶
type ControlMode ¶
type ControlMode string
const ( ControlStatic ControlMode = "static" ControlAdaptive ControlMode = "adaptive" ControlFallback ControlMode = "fixed_fallback" )
type DeliveryFaults ¶
type DeliveryFaults struct{ LostTerminals, IncompleteExchanges uint64 }
type DialOptions ¶
type DialOptions struct {
Client ClientConfig
TLS TLSOptions
QUIC QUICConfig
}
type DrainReport ¶
type DrainReport struct {
Before, After ServerStats
MemoryBefore, MemoryAfter MemoryStats
PriorFaults, AddedFaults DeliveryFaults
TotalFaults DeliveryFaults
Quiescent bool
}
DrainReport separates resource completion from cumulative delivery health. Before is captured under the admission lock when this drain seals admission. Quiescent joins framework readers and handlers, not external application work or remote consumption/commit. Memory snapshots use their own budget locks; they are not atomic with the RPC counters. No history is reset by drain.
type Endpoint ¶
type FeedbackConfig ¶
type FeedbackMethod ¶
type FeedbackStats ¶
type FeedbackStats struct {
Enabled bool
Accepted, Ignored, Limited uint64
Methods []FeedbackMethod
}
type GovernanceConfig ¶
type GovernanceConfig struct {
MaxExecuting, QueueCapacity, SampleWindow int
QueueTimeout, FeedbackTTL time.Duration
QueuePolicy QueuePolicy
Adaptive, Feedback bool
Methods []MethodPolicy
}
type GovernanceSnapshot ¶
type GovernanceSnapshot struct {
Enabled, Adaptive bool
Epoch string
Executing, Queued int
Methods []MethodState
Decisions []ControlDecision
DroppedDecisions uint64
}
type HealthStatus ¶
type Interceptor ¶
Interceptor enters once, in registration order. Finish runs once in reverse order, with no framework mutex held. Server finishes measure handler lifecycle; client stream finishes observe protocol completion, not user consumption. Hooks are cooperative user code and must return; panics become Internal.
func Credentials ¶
func Credentials(provider func(context.Context) (Metadata, error)) Interceptor
Credentials supplies outgoing call metadata before serialization. Providers must honor ctx, and bearer credentials should use authenticated TLS/QUIC.
func LoggingInterceptor ¶
func LoggingInterceptor(logger *slog.Logger) Interceptor
type MemoryAccount ¶
type MemoryAccount struct {
// contains filtered or unexported fields
}
func (*MemoryAccount) ID ¶
func (a *MemoryAccount) ID() uint64
func (*MemoryAccount) Release ¶
func (a *MemoryAccount) Release() error
Release removes a quiescent account. Closing a socket alone cannot forgive leases held by a user codec or an unread stream. Retire never frees bytes.
func (*MemoryAccount) Retire ¶
func (a *MemoryAccount) Retire()
func (*MemoryAccount) Snapshot ¶
func (a *MemoryAccount) Snapshot() MemoryAccountStats
type MemoryAccountStats ¶
type MemoryAccountStats struct {
ID uint64
Retired, Bound, OwnerClosed, Released bool
Memory MemoryStats
DataBytes, TotalBytes int64
Leases, EncodingWaiters int
Unread BufferStats
}
type MemoryConfig ¶
type MemoryConfig struct{ ReceiveBytes, SendBytes, ControlBytes, EncodingBytes int64 }
MemoryConfig bounds retained framework record buffers, not arbitrary application allocations, decoded response objects, QUIC internals or RSS.
type MemoryGroupStats ¶
type MemoryGroupStats struct {
Accounts, Leases, EncodingWaiters int
Bytes MemoryUsage
DataBytes int64
Unread BufferUsage // Current group occupancy; peaks are reported at pool/account level.
}
type MemoryPool ¶
type MemoryPool struct {
// contains filtered or unexported fields
}
MemoryPool owns only accounting, never sockets, request tables or user buffers. All attached local and aggregate budgets use this single mutex. No pool method calls into a connection or routing, which keeps the lock order one-way.
func NewMemoryPool ¶
func NewMemoryPool(cfg MemoryPoolConfig, maxAccounts int) (*MemoryPool, error)
func (*MemoryPool) Accounts ¶
func (p *MemoryPool) Accounts() []MemoryAccountStats
func (*MemoryPool) CheckClient ¶
func (p *MemoryPool) CheckClient(cfg ClientConfig) error
CheckClient validates capacity for a maximum prepared OPEN plus its send lease. It does not reserve an account or bind it to a client.
func (*MemoryPool) NewAccount ¶
func (p *MemoryPool) NewAccount() (*MemoryAccount, error)
func (*MemoryPool) Seal ¶
func (p *MemoryPool) Seal()
func (*MemoryPool) Stats ¶
func (p *MemoryPool) Stats() MemoryPoolStats
type MemoryPoolConfig ¶
type MemoryPoolConfig struct {
Memory MemoryConfig
DataBytes int64
}
MemoryPoolConfig limits aggregate framework buffers. DataBytes covers encoding, receive and send together. Control receive/send each retain a separate bound. Zero values use 32 MiB data, 16 MiB per data class and 64 KiB per control class.
type MemoryPoolStats ¶
type MemoryPoolStats struct {
Memory MemoryStats
Data, Total ByteStats
Active, Retired MemoryGroupStats
Unread BufferStats
Accounts, PeakAccounts, Limit int
Created, Released uint64
Sealed bool
}
type MemoryStats ¶
type MemoryStats struct{ Receive, Send, ControlReceive, ControlSend, Encoding ByteStats }
type MemoryUsage ¶
type MemoryUsage struct{ Receive, Send, ControlReceive, ControlSend, Encoding int64 }
type Metadata ¶
Metadata is UTF-8 call metadata. Keys are lowercase ASCII; credentials are untrusted until Authenticate validates them. Values are never logged by core.
func IncomingMetadata ¶
func OutgoingMetadata ¶
type MetadataCapture ¶
type MetadataCapture struct {
// contains filtered or unexported fields
}
MetadataCapture reads response trailers safely, including while a call runs. Trailers become available with END; they are not initial response headers.
func (*MetadataCapture) Snapshot ¶
func (c *MetadataCapture) Snapshot() Metadata
type MethodInfo ¶
type MethodPolicy ¶
type MethodState ¶
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics exports bounded Prometheus exposition. Auth/body/identity values are never labels. Server hooks measure worker time; core admission/fault gauges are exported independently so refusals remain visible.
func NewMetrics ¶
func (*Metrics) AttachServer ¶
func (*Metrics) Interceptor ¶
func (m *Metrics) Interceptor() Interceptor
type PipelineConfig ¶
type PipelineConfig struct {
Timeout time.Duration
MaxInFlight int
RateLimiter *RateLimiter
Interceptors []Interceptor
Retry RetryPolicy
}
type Pressure ¶
type Pressure struct {
Version int `json:"v"`
Epoch string `json:"epoch"`
Sequence uint64 `json:"seq"`
TTLMillis int64 `json:"ttl_ms"`
Method string `json:"method"`
Limit, Running, Queued, PeersDemand, Recommended int
ReceiveUsed, ReceiveLimit int64
}
Pressure is advisory metadata from an authenticated/configured peer, not a distributed lease, reservation, tenant identity or authorization decision.
type ProtobufMethod ¶
type ProtobufMethod struct {
Path string
NewRequest func() proto.Message
Unary func(context.Context, proto.Message) (proto.Message, error)
Stream func(context.Context, proto.Message, func(proto.Message) error) error
}
ProtobufMethod binds one method to fresh request messages. Exactly one of Unary or Stream must be set. Generated registration supplies typed adapters.
type ProtobufRequest ¶
type ProtobufRequest struct {
// contains filtered or unexported fields
}
ProtobufRequest selects binary Protobuf for one call, including its responses. Construct it with Protobuf. JSON remains the default for unwrapped requests.
func Protobuf ¶
func Protobuf(message proto.Message) ProtobufRequest
Protobuf wraps a message without encoding it. Admission and byte reservation still happen before user message code runs. Do not mutate a message during Call or Stream creation; the Protobuf runtime does not support concurrent mutation.
type QUICClient ¶
type QUICClient struct {
// contains filtered or unexported fields
}
QUICClient owns one authenticated physical session. Each Call/Stream opens an independent native exchange, with no retries or hidden TCP downgrade.
func DialQUIC ¶
func DialQUIC(ctx context.Context, address string, security TLSOptions, options QUICConfig, cfg ClientConfig) (*QUICClient, error)
func (*QUICClient) AdmissionStats ¶
func (c *QUICClient) AdmissionStats() AdmissionStats
func (*QUICClient) BufferStats ¶
func (c *QUICClient) BufferStats() BufferStats
func (*QUICClient) Capabilities ¶
func (c *QUICClient) Capabilities() Capabilities
func (*QUICClient) Close ¶
func (c *QUICClient) Close()
func (*QUICClient) CompressionStats ¶
func (c *QUICClient) CompressionStats() CompressionStats
func (*QUICClient) FeedbackStats ¶
func (c *QUICClient) FeedbackStats() FeedbackStats
func (*QUICClient) MemoryStats ¶
func (c *QUICClient) MemoryStats() MemoryStats
func (*QUICClient) OpenStream ¶
func (*QUICClient) Stats ¶
func (c *QUICClient) Stats() QUICStats
type QUICConfig ¶
type QUICListener ¶
type QUICListener struct {
// contains filtered or unexported fields
}
QUICListener explicitly owns a packet socket and transport. Stopping new handshakes is separate from closing accepted sessions and the UDP socket.
func ListenQUIC ¶
func ListenQUIC(address string, security TLSOptions, options QUICConfig) (*QUICListener, error)
func (*QUICListener) Addr ¶
func (l *QUICListener) Addr() net.Addr
func (*QUICListener) Close ¶
func (l *QUICListener) Close() error
type QueuePolicy ¶
type QueuePolicy string
const ( FIFO QueuePolicy = "fifo" MethodFair QueuePolicy = "method_fair" )
type RateLimitError ¶
type RateLimitError struct{ Method string }
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
func (*RateLimitError) Unwrap ¶
func (e *RateLimitError) Unwrap() error
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
func NewRateLimiter ¶
func NewRateLimiter(policies map[string]RateSpec) (*RateLimiter, error)
NewRateLimiter compiles a bounded static policy table. "*" is a shared total bucket, not a dynamically growing per-method or per-tenant cache.
func (*RateLimiter) Allow ¶
func (r *RateLimiter) Allow(method string) error
func (*RateLimiter) Stats ¶
func (r *RateLimiter) Stats() RateStats
type Receiver ¶
Receiver is shared by direct and routing-managed streams. Close releases a stream early; EOF and errors also let a routing stream release its references.
type RetryPolicy ¶
type Sender ¶
type Sender struct {
// contains filtered or unexported fields
}
Sender is valid only during its handler invocation. Send is serialized and waits for receiver credits without blocking the connection's control reader. Body is preencoded using the registered method's codec. Protobuf handlers normally use the typed send callback instead of calling Sender directly.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server owns a listener after Serve succeeds, every accepted connection, and every admitted handler. Handler registration freezes at Serve.
func NewServer ¶
func NewServer(cfg ServerConfig) (*Server, error)
func (*Server) CompressionStats ¶
func (s *Server) CompressionStats() CompressionStats
func (*Server) Drain ¶
Drain seals admission under the same lock used by admit. Successful normal results are kept alive through receipt ACK; the caller deadline bounds drain.
func (*Server) DrainWithReport ¶
func (s *Server) DrainWithReport(ctx context.Context) (report DrainReport, err error)
DrainWithReport retains both a context failure and ErrDelivery when present. With only cumulative delivery faults it returns ErrDelivery, as Drain does.
Example ¶
package main
import (
"context"
"fmt"
"net"
"time"
rpc "github.com/KanaDoodle/KanaRPC"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
s, err := rpc.NewServer(rpc.ServerConfig{})
if err != nil {
panic(err)
}
if err := rpc.RegisterUnary(s, "/example/echo", func(_ context.Context, n int) (int, error) { return n, nil }); err != nil {
panic(err)
}
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
done := make(chan error, 1)
go func() { done <- s.Serve(l) }()
defer s.Close()
c, err := rpc.Dial(ctx, l.Addr().String(), rpc.ClientConfig{})
if err != nil {
panic(err)
}
defer c.Close()
var out int
if err := c.Call(ctx, "/example/echo", 42, &out); err != nil {
panic(err)
}
// Use a fresh shutdown context, not a canceled request context.
shutdown, stop := context.WithTimeout(context.Background(), time.Second)
defer stop()
report, err := s.DrainWithReport(shutdown)
if err != nil {
panic(err)
} // Inspect errors.Is(err, rpc.ErrDelivery) and ctx errors separately.
if err := <-done; err != nil {
panic(err)
}
fmt.Println(out, report.Quiescent, report.TotalFaults.LostTerminals)
}
Output: 42 true 0
func (*Server) Governance ¶
func (s *Server) Governance() GovernanceSnapshot
func (*Server) HandleStream ¶
func (s *Server) HandleStream(path string, h StreamHandler) error
func (*Server) HandleUnary ¶
func (s *Server) HandleUnary(path string, h UnaryHandler) error
func (*Server) Health ¶
func (s *Server) Health() HealthStatus
func (*Server) HealthHandler ¶
HealthHandler is for an explicitly bound administrative listener.
func (*Server) MemoryStats ¶
func (s *Server) MemoryStats() MemoryStats
func (*Server) Methods ¶
func (s *Server) Methods() []MethodInfo
func (*Server) ResetAdaptive ¶
ResetAdaptive is a local operator action, never an automatic business retry. Existing handlers keep their slots but cannot sample into the new generation.
func (*Server) Serve ¶
Serve transfers listener ownership only if the server has not started or closed. It returns when acceptance stops; Drain/Wait cover admitted work.
func (*Server) ServeQUIC ¶
func (s *Server) ServeQUIC(listener *QUICListener) error
func (*Server) ServeTLS ¶
func (s *Server) ServeTLS(listener net.Listener, options TLSOptions) error
ServeTLS counts accepted sockets, including pending bounded handshakes, against MaxConnections. A stalled handshake does not block other accepts.
func (*Server) SetServing ¶
func (*Server) Stats ¶
func (s *Server) Stats() ServerStats
type ServerConfig ¶
type ServerConfig struct {
Compression *CompressionConfig
TCPKeepAlive *TCPKeepAliveConfig
Interceptors []Interceptor
Authenticate Authenticator
RateLimiter *RateLimiter
Trace *TraceRecorder // nil disables the bounded local decision journal
Governance *GovernanceConfig
Memory MemoryConfig
IO IOConfig
MaxConnections int
// MaxInFlight includes queued work, handlers and terminal-ACK/FIN waiters.
MaxInFlight int
MaxPerConnection int
MaxRequestDuration time.Duration
AckTimeout time.Duration
}
type ServerOutcomes ¶
type ServerOutcomes struct {
CapacityRejected, PolicyRejected, DrainingRejected, InvalidRejected, NotFoundRejected uint64
CancelRequests, RequestDeadlines, TransportAborts, ShutdownAborts, BudgetAborts uint64
// ReceiptsResolved equals Delivered + LostTerminals + the two outcomes below.
// An active receipt wait is not included until it is settled.
ReceiptsResolved, ReceiptsCanceled, ReceiptsDeadlineExceeded uint64
}
ServerOutcomes contains cumulative observations, not disjoint RPC totals. CancelRequests counts the first CANCEL observed for an active execution, even after END; it does not assert cancellation won. Business status codes do not increment these counters. Byte refusals live in MemoryStats.Rejected.
type ServerStats ¶
type ServerStats struct {
// Canceled is the legacy handler-status count, including deadline statuses.
// Outcomes records protocol observations separately from application codes.
Outcomes ServerOutcomes
Queued int
IncompleteExchanges uint64
NativeStreams int
Connections, InFlight, Executing int
Admitted, Completed, Rejected, Canceled, Delivered, LostTerminals uint64
}
type ServiceCaller ¶
type ServiceCaller interface {
Call(context.Context, string, any, any) error
OpenStream(context.Context, string, any) (Receiver, error)
}
ServiceCaller is the transport-independent interface used by generated SDKs. Implementations honor Protobuf(request) and preserve stream ownership.
func AsServiceCaller ¶
func AsServiceCaller(c Caller) ServiceCaller
AsServiceCaller bridges the older concrete-Stream Caller contract without changing implementations or introducing a second call lifecycle.
type StreamHandler ¶
type TCPKeepAliveConfig ¶
type TraceConfig ¶
type TraceConfig struct {
Capacity int
SampleEvery uint64 // deterministic sampling by local channel/request pair
}
TraceRecorder is an opt-in, bounded local decision journal, not a distributed trace or delivery ledger. Writers never wait for the reader or call user code. Dropped/overwritten events make incomplete timelines explicit.
type TraceEvent ¶
type TraceRecorder ¶
type TraceRecorder struct {
// contains filtered or unexported fields
}
func NewTraceRecorder ¶
func NewTraceRecorder(c TraceConfig) (*TraceRecorder, error)
func (*TraceRecorder) Snapshot ¶
func (r *TraceRecorder) Snapshot(after uint64, limit int) TraceSnapshot
Snapshot copies at most 1024 events. RPC writers skip a busy journal instead of waiting behind this copy. Memory is fixed at construction; no body is kept.
type TraceRef ¶
type TraceSnapshot ¶
type TraceSnapshot struct {
Events []TraceEvent `json:"events"`
Capacity int `json:"capacity"`
SampleEvery uint64 `json:"sample_every"`
Last uint64 `json:"last"`
Oldest uint64 `json:"oldest"`
Dropped uint64 `json:"dropped"`
Overwritten uint64 `json:"overwritten"`
SampledOut uint64 `json:"sampled_out"`
Gap bool `json:"gap"`
}
type UnaryHandler ¶
type UnaryHandler func(context.Context, json.RawMessage) (json.RawMessage, error)
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
governance-lab
command
governance-lab measures real loopback RPC around a bounded timer/slot fixture.
|
governance-lab measures real loopback RPC around a bounded timer/slot fixture. |
|
kanarpc
command
kanarpc is a JSON call/stream/health/method-list CLI for KNR2 endpoints.
|
kanarpc is a JSON call/stream/health/method-list CLI for KNR2 endpoints. |
|
lifecycle-demo
command
lifecycle-demo exercises the v2 transport with two owned loopback processes.
|
lifecycle-demo exercises the v2 transport with two owned loopback processes. |
|
pool-lab
command
pool-lab uses resource-lab's real workers and a local snapshot fixture.
|
pool-lab uses resource-lab's real workers and a local snapshot fixture. |
|
production-demo
command
production-demo executes the complete local integration chain.
|
production-demo executes the complete local integration chain. |
|
protobuf-demo
command
protobuf-demo runs a generated SDK against a real loopback TCP server.
|
protobuf-demo runs a generated SDK against a real loopback TCP server. |
|
protoc-gen-kanarpc
command
protoc-gen-kanarpc generates typed KanaRPC clients and service registration.
|
protoc-gen-kanarpc generates typed KanaRPC clients and service registration. |
|
resource-lab
command
resource-lab is an owned loopback resource experiment, not model inference.
|
resource-lab is an owned loopback resource experiment, not model inference. |
|
routing-lab
command
routing-lab is an independent client for transport-lab workers.
|
routing-lab is an independent client for transport-lab workers. |
|
showcase
command
showcase runs a local RPC governance console with embedded web assets.
|
showcase runs a local RPC governance console with embedded web assets. |
|
transport-lab
command
transport-lab uses integer IDs and fixed JSON chunks, never a model backend.
|
transport-lab uses integer IDs and fixed JSON chunks, never a model backend. |
|
Package discovery owns explicit etcd registrations and fresh resolver snapshots.
|
Package discovery owns explicit etcd registrations and fresh resolver snapshots. |
|
examples
|
|
|
internal
|
|
|
netfault
Package netfault is an owned single-client UDP test relay.
|
Package netfault is an owned single-client UDP test relay. |
|
protogen
Package protogen emits Go bindings for KanaRPC unary and server-streaming RPCs.
|
Package protogen emits Go bindings for KanaRPC unary and server-streaming RPCs. |
|
testcert
Package testcert creates ephemeral localhost credentials for tests and labs.
|
Package testcert creates ephemeral localhost credentials for tests and labs. |
|
wire
Package wire implements the experimental KanaRPC v2 record format.
|
Package wire implements the experimental KanaRPC v2 record format. |
|
Package observability adapts the common KanaRPC lifecycle hook to OTel.
|
Package observability adapts the common KanaRPC lifecycle hook to OTel. |
|
Package routing owns discovery-driven connection lifetimes.
|
Package routing owns discovery-driven connection lifetimes. |