rpc

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2025 License: MIT Imports: 33 Imported by: 0

Documentation

Overview

Package rpc provides error detail handling for different protocols.

Package rpc provides error codes and handling for Connect/gRPC protocols.

Package rpc provides interceptor implementations.

Package rpc provides retry policy support according to gRPC specification.

Package rpc provides retry interceptor implementation.

Package rpc provides the main public API for the hyperway RPC library.

Package rpc provides streaming RPC support.

Index

Constants

View Source
const (
	CompressionIdentity = ""     // No compression
	CompressionGzip     = "gzip" // gzip compression
	CompressionBrotli   = "br"   // Brotli compression
	CompressionZstd     = "zstd" // Zstandard compression
)

Compression algorithms

View Source
const (
	// Standard JSON-RPC 2.0 error codes
	JSONRPCParseError     = -32700 // Invalid JSON was received by the server
	JSONRPCInvalidRequest = -32600 // The JSON sent is not a valid Request object
	JSONRPCMethodNotFound = -32601 // The method does not exist / is not available
	JSONRPCInvalidParams  = -32602 // Invalid method parameter(s)
	JSONRPCInternalError  = -32603 // Internal JSON-RPC error

	// Server error codes (reserved range: -32000 to -32099)
	JSONRPCServerError = -32000 // Generic server error
)

JSON-RPC 2.0 Error Codes

View Source
const (
	// DefaultJSONRPCPath is the default path for JSON-RPC endpoints
	DefaultJSONRPCPath = "/jsonrpc"
	// DefaultJSONRPCBatchLimit is the default batch request limit
	DefaultJSONRPCBatchLimit = 50
)
View Source
const (
	// DefaultMaxReceiveMessageSize is the default maximum message size that can be received (4MB)
	DefaultMaxReceiveMessageSize = 4 * 1024 * 1024
	// DefaultMaxSendMessageSize is the default maximum message size that can be sent (4MB)
	DefaultMaxSendMessageSize = 4 * 1024 * 1024
)

Default message size limits (matching gRPC defaults)

Variables

This section is empty.

Functions

func ClearHandlerCache

func ClearHandlerCache()

ClearCache clears the handler cache (useful for testing)

func GetHandlerContext added in v0.3.0

func GetHandlerContext(ctx context.Context) *handlerContext

GetHandlerContext retrieves the handler context from a context.Context

func IsBatchRequest added in v0.4.0

func IsBatchRequest(data []byte) bool

IsBatchRequest checks if the raw message is a batch request

func MustRegister

func MustRegister[TIn, TOut any](svc *Service, handler Handler[TIn, TOut])

MustRegister registers a unary RPC method with automatic name generation and panics on error.

func MustRegisterAs added in v0.8.0

func MustRegisterAs[TIn, TOut any](svc *Service, name string, handler Handler[TIn, TOut])

MustRegisterAs registers a unary RPC method with an explicit name and panics on error.

func MustRegisterBidiStream added in v0.7.0

func MustRegisterBidiStream[TIn, TOut any](svc *Service, handler BidiStreamHandler[TIn, TOut])

MustRegisterBidiStream registers a bidirectional streaming RPC method with automatic name generation and panics on error.

func MustRegisterBidiStreamAs added in v0.8.0

func MustRegisterBidiStreamAs[TIn, TOut any](svc *Service, name string, handler BidiStreamHandler[TIn, TOut])

MustRegisterBidiStreamAs registers a bidirectional streaming RPC method with an explicit name and panics on error.

func MustRegisterClientStream added in v0.7.0

func MustRegisterClientStream[TIn, TOut any](svc *Service, handler ClientStreamHandler[TIn, TOut])

MustRegisterClientStream registers a client-streaming RPC method with automatic name generation and panics on error.

func MustRegisterClientStreamAs added in v0.8.0

func MustRegisterClientStreamAs[TIn, TOut any](svc *Service, name string, handler ClientStreamHandler[TIn, TOut])

MustRegisterClientStreamAs registers a client-streaming RPC method with an explicit name and panics on error.

func MustRegisterServerStream added in v0.3.0

func MustRegisterServerStream[TIn, TOut any](svc *Service, handler ServerStreamHandler[TIn, TOut])

MustRegisterServerStream registers a server-streaming RPC method with automatic name generation and panics on error.

func MustRegisterServerStreamAs added in v0.8.0

func MustRegisterServerStreamAs[TIn, TOut any](svc *Service, name string, handler ServerStreamHandler[TIn, TOut])

MustRegisterServerStreamAs registers a server-streaming RPC method with an explicit name and panics on error.

func NewHandler added in v0.6.1

func NewHandler(services ...*Service) (http.Handler, error)

NewHandler creates an HTTP handler for the service.

func Register

func Register[TIn, TOut any](svc *Service, handler Handler[TIn, TOut]) error

Register registers a unary RPC method with automatic name generation.

func RegisterAs added in v0.8.0

func RegisterAs[TIn, TOut any](svc *Service, name string, handler Handler[TIn, TOut]) error

RegisterAs registers a unary RPC method with an explicit name.

func RegisterBidiStream added in v0.7.0

func RegisterBidiStream[TIn, TOut any](svc *Service, handler BidiStreamHandler[TIn, TOut]) error

RegisterBidiStream registers a bidirectional streaming RPC method with automatic name generation.

func RegisterBidiStreamAs added in v0.8.0

func RegisterBidiStreamAs[TIn, TOut any](svc *Service, name string, handler BidiStreamHandler[TIn, TOut]) error

RegisterBidiStreamAs registers a bidirectional streaming RPC method with an explicit name.

func RegisterClientStream added in v0.7.0

func RegisterClientStream[TIn, TOut any](svc *Service, handler ClientStreamHandler[TIn, TOut]) error

RegisterClientStream registers a client-streaming RPC method with automatic name generation.

func RegisterClientStreamAs added in v0.8.0

func RegisterClientStreamAs[TIn, TOut any](svc *Service, name string, handler ClientStreamHandler[TIn, TOut]) error

RegisterClientStreamAs registers a client-streaming RPC method with an explicit name.

func RegisterCompressor

func RegisterCompressor(c Compressor)

RegisterCompressor registers a compressor

func RegisterServerStream added in v0.3.0

func RegisterServerStream[TIn, TOut any](svc *Service, handler ServerStreamHandler[TIn, TOut]) error

RegisterServerStream registers a server-streaming RPC method with automatic name generation.

func RegisterServerStreamAs added in v0.8.0

func RegisterServerStreamAs[TIn, TOut any](svc *Service, name string, handler ServerStreamHandler[TIn, TOut]) error

RegisterServerStreamAs registers a server-streaming RPC method with an explicit name.

func ValidateRetryPolicy

func ValidateRetryPolicy(policy *RetryPolicy) error

ValidateRetryPolicy validates a retry policy according to gRPC spec.

func ValidateRetryThrottling

func ValidateRetryThrottling(throttling *RetryThrottling) error

ValidateRetryThrottling validates retry throttling configuration.

Types

type BidiStream added in v0.3.0

type BidiStream[TIn, TOut any] interface {
	// Send sends a message to the client.
	Send(*TOut) error
	// Recv receives a message from the client.
	Recv() (*TIn, error)
	// Context returns the context for this stream.
	Context() context.Context
}

BidiStream represents a bidirectional stream.

type BidiStreamHandler added in v0.3.0

type BidiStreamHandler[TIn, TOut any] func(context.Context, BidiStream[TIn, TOut]) error

BidiStreamHandler handles bidirectional streaming RPCs.

type BrotliCompressor added in v0.5.0

type BrotliCompressor struct{}

BrotliCompressor implements Brotli compression

func (*BrotliCompressor) Compress added in v0.5.0

func (b *BrotliCompressor) Compress(data []byte) ([]byte, error)

func (*BrotliCompressor) Decompress added in v0.5.0

func (b *BrotliCompressor) Decompress(data []byte) ([]byte, error)

func (*BrotliCompressor) Name added in v0.5.0

func (b *BrotliCompressor) Name() string

type ClientStream added in v0.3.0

type ClientStream[T any] interface {
	// Recv receives a message from the client.
	Recv() (*T, error)
	// Context returns the context for this stream.
	Context() context.Context
}

ClientStream represents a client-side stream.

type ClientStreamHandler added in v0.3.0

type ClientStreamHandler[TIn, TOut any] func(context.Context, ClientStream[TIn]) (*TOut, error)

ClientStreamHandler handles client-streaming RPCs.

type Code

type Code string

Code represents a Connect/gRPC error code.

const (
	CodeCanceled           Code = "canceled"
	CodeUnknown            Code = "unknown"
	CodeInvalidArgument    Code = "invalid_argument"
	CodeDeadlineExceeded   Code = "deadline_exceeded"
	CodeNotFound           Code = "not_found"
	CodeAlreadyExists      Code = "already_exists"
	CodePermissionDenied   Code = "permission_denied"
	CodeResourceExhausted  Code = "resource_exhausted"
	CodeFailedPrecondition Code = "failed_precondition"
	CodeAborted            Code = "aborted"
	CodeOutOfRange         Code = "out_of_range"
	CodeUnimplemented      Code = "unimplemented"
	CodeInternal           Code = "internal"
	CodeUnavailable        Code = "unavailable"
	CodeDataLoss           Code = "data_loss"
	CodeUnauthenticated    Code = "unauthenticated"
)

Standard Connect/gRPC error codes.

func (Code) HTTPStatusCode

func (c Code) HTTPStatusCode() int

HTTPStatusCode returns the HTTP status code for the error code. For Connect protocol, most errors return 200 OK with error in body. This is used for non-Connect protocol responses.

type Compressor

type Compressor interface {
	Compress(data []byte) ([]byte, error)
	Decompress(data []byte) ([]byte, error)
	Name() string
}

Compressor interface for compression algorithms

func GetCompressor

func GetCompressor(name string) (Compressor, bool)

GetCompressor returns a compressor by name

type ConnectOption added in v0.6.0

type ConnectOption func(*connectProtocol)

ConnectOption configures Connect protocol

func WithConnectJSON added in v0.6.0

func WithConnectJSON(allow bool) ConnectOption

WithConnectJSON enables/disables JSON support for Connect

func WithConnectProto added in v0.6.0

func WithConnectProto(allow bool) ConnectOption

WithConnectProto enables/disables Protobuf support for Connect

type ConnectSettings added in v0.6.0

type ConnectSettings struct {
	AllowJSON  bool
	AllowProto bool
}

ConnectSettings holds Connect-specific settings

type ContextHelper added in v0.8.0

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

ContextHelper provides a fluent API for working with handler context.

func Context added in v0.8.0

func Context(ctx context.Context) *ContextHelper

Context creates a new ContextHelper from a context.

func (*ContextHelper) Authorization added in v0.8.0

func (c *ContextHelper) Authorization() string

Authorization gets the Authorization header value.

func (*ContextHelper) BearerToken added in v0.8.0

func (c *ContextHelper) BearerToken() string

BearerToken extracts the bearer token from the Authorization header. Returns empty string if the header is not in the format "Bearer <token>".

func (*ContextHelper) ClientIP added in v0.8.0

func (c *ContextHelper) ClientIP() string

ClientIP attempts to get the client's IP address from common headers.

func (*ContextHelper) Context added in v0.8.0

func (c *ContextHelper) Context() context.Context

Context returns the underlying context.Context.

func (*ContextHelper) HandlerContext added in v0.8.0

func (c *ContextHelper) HandlerContext() *handlerContext

HandlerContext returns the underlying handlerContext. This is useful for advanced use cases that need direct access.

func (*ContextHelper) HasHeader added in v0.8.0

func (c *ContextHelper) HasHeader(key string) bool

HasHeader checks if a header exists.

func (*ContextHelper) Header added in v0.8.0

func (c *ContextHelper) Header(key string) string

Header gets a request header value. Returns the first value if multiple values exist.

func (*ContextHelper) HeaderValues added in v0.8.0

func (c *ContextHelper) HeaderValues(key string) []string

HeaderValues gets all values for a request header.

func (*ContextHelper) Headers added in v0.8.0

func (c *ContextHelper) Headers() map[string][]string

Headers gets all request headers.

func (*ContextHelper) IsConnect added in v0.8.0

func (c *ContextHelper) IsConnect() bool

IsConnect checks if the current request is using Connect protocol.

func (*ContextHelper) IsGRPC added in v0.8.0

func (c *ContextHelper) IsGRPC() bool

IsGRPC checks if the current request is using gRPC protocol.

func (*ContextHelper) IsGRPCWeb added in v0.8.0

func (c *ContextHelper) IsGRPCWeb() bool

IsGRPCWeb checks if the current request is using gRPC-Web protocol.

func (*ContextHelper) IsJSONRPC added in v0.8.0

func (c *ContextHelper) IsJSONRPC() bool

IsJSONRPC checks if the current request is using JSON-RPC protocol.

func (*ContextHelper) Metadata added in v0.8.0

func (c *ContextHelper) Metadata(key string) string

Metadata gets a metadata value from the request. Looks for headers with "x-metadata-" prefix.

func (*ContextHelper) MustValidate added in v0.8.0

func (c *ContextHelper) MustValidate()

MustValidate runs all validations and panics if any fail.

func (*ContextHelper) RequireHeader added in v0.8.0

func (c *ContextHelper) RequireHeader(key string) *ContextHelper

RequireHeader adds a validation that the specified header must exist.

func (*ContextHelper) RequireHeaders added in v0.8.0

func (c *ContextHelper) RequireHeaders(keys ...string) *ContextHelper

RequireHeaders adds validations that all specified headers must exist.

func (*ContextHelper) RequireMetadata added in v0.8.0

func (c *ContextHelper) RequireMetadata(key string) *ContextHelper

RequireMetadata adds a validation that the specified metadata must exist.

func (*ContextHelper) SetHeader added in v0.8.0

func (c *ContextHelper) SetHeader(key, value string) *ContextHelper

SetHeader sets a response header.

func (*ContextHelper) SetHeaders added in v0.8.0

func (c *ContextHelper) SetHeaders(headers map[string]string) *ContextHelper

SetHeaders sets multiple response headers.

func (*ContextHelper) SetMetadata added in v0.8.0

func (c *ContextHelper) SetMetadata(key, value string) *ContextHelper

SetMetadata sets a metadata value in the context. Metadata is stored in the response headers with a "x-metadata-" prefix.

func (*ContextHelper) SetTrailer added in v0.8.0

func (c *ContextHelper) SetTrailer(key, value string) *ContextHelper

SetTrailer sets a response trailer.

func (*ContextHelper) SetTrailers added in v0.8.0

func (c *ContextHelper) SetTrailers(trailers map[string]string) *ContextHelper

SetTrailers sets multiple response trailers.

func (*ContextHelper) UserAgent added in v0.8.0

func (c *ContextHelper) UserAgent() string

UserAgent gets the User-Agent header.

func (*ContextHelper) Validate added in v0.8.0

func (c *ContextHelper) Validate() error

Validate runs all accumulated validations. Returns the first error encountered, or nil if all validations pass.

func (*ContextHelper) WithValue added in v0.8.0

func (c *ContextHelper) WithValue(key, value any) *ContextHelper

WithValue returns a new ContextHelper with the given key-value pair added to the context.

type Error

type Error struct {
	Code    Code           `json:"code"`
	Message string         `json:"message"`
	Details map[string]any `json:"details,omitempty"`
}

Error represents a Connect/gRPC error with code and message.

func ErrDeadlineExceeded

func ErrDeadlineExceeded(message string) *Error

ErrDeadlineExceeded creates a deadline exceeded error.

func ErrInternal

func ErrInternal(message string) *Error

ErrInternal creates an internal error.

func ErrInvalidArgument

func ErrInvalidArgument(message string) *Error

ErrInvalidArgument creates an invalid argument error.

func ErrNotFound

func ErrNotFound(message string) *Error

ErrNotFound creates a not found error.

func ErrPermissionDenied

func ErrPermissionDenied(message string) *Error

ErrPermissionDenied creates a permission denied error.

func ErrUnauthenticated

func ErrUnauthenticated(message string) *Error

ErrUnauthenticated creates an unauthenticated error.

func ErrUnimplemented

func ErrUnimplemented(message string) *Error

ErrUnimplemented creates an unimplemented error.

func NewError

func NewError(code Code, message string) *Error

NewError creates a new Error with the given code and message.

func NewErrorf

func NewErrorf(code Code, format string, args ...any) *Error

NewErrorf creates a new Error with the given code and formatted message.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) WithDetails

func (e *Error) WithDetails(details map[string]any) *Error

WithDetails adds details to the error.

type ErrorBuilder added in v0.8.0

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

ErrorBuilder provides a fluent API for building errors.

func Aborted added in v0.8.0

func Aborted(message string) *ErrorBuilder

Aborted creates an ErrorBuilder with CodeAborted.

func AlreadyExists added in v0.8.0

func AlreadyExists(message string) *ErrorBuilder

AlreadyExists creates an ErrorBuilder with CodeAlreadyExists.

func Canceled added in v0.8.0

func Canceled(message string) *ErrorBuilder

Canceled creates an ErrorBuilder with CodeCanceled.

func DataLoss added in v0.8.0

func DataLoss(message string) *ErrorBuilder

DataLoss creates an ErrorBuilder with CodeDataLoss.

func DeadlineExceeded added in v0.8.0

func DeadlineExceeded(message string) *ErrorBuilder

DeadlineExceeded creates an ErrorBuilder with CodeDeadlineExceeded.

func FailedPrecondition added in v0.8.0

func FailedPrecondition(message string) *ErrorBuilder

FailedPrecondition creates an ErrorBuilder with CodeFailedPrecondition.

func Internal added in v0.8.0

func Internal(message string) *ErrorBuilder

Internal creates an ErrorBuilder with CodeInternal.

func InvalidArgument added in v0.8.0

func InvalidArgument(message string) *ErrorBuilder

InvalidArgument creates an ErrorBuilder with CodeInvalidArgument.

func NewErrorBuilder added in v0.8.0

func NewErrorBuilder() *ErrorBuilder

NewErrorBuilder creates a new ErrorBuilder.

func NotFound added in v0.8.0

func NotFound(message string) *ErrorBuilder

NotFound creates an ErrorBuilder with CodeNotFound.

func OutOfRange added in v0.8.0

func OutOfRange(message string) *ErrorBuilder

OutOfRange creates an ErrorBuilder with CodeOutOfRange.

func PermissionDenied added in v0.8.0

func PermissionDenied(message string) *ErrorBuilder

PermissionDenied creates an ErrorBuilder with CodePermissionDenied.

func ResourceExhausted added in v0.8.0

func ResourceExhausted(message string) *ErrorBuilder

ResourceExhausted creates an ErrorBuilder with CodeResourceExhausted.

func Unauthenticated added in v0.8.0

func Unauthenticated(message string) *ErrorBuilder

Unauthenticated creates an ErrorBuilder with CodeUnauthenticated.

func Unavailable added in v0.8.0

func Unavailable(message string) *ErrorBuilder

Unavailable creates an ErrorBuilder with CodeUnavailable.

func Unimplemented added in v0.8.0

func Unimplemented(message string) *ErrorBuilder

Unimplemented creates an ErrorBuilder with CodeUnimplemented.

func (*ErrorBuilder) Build added in v0.8.0

func (e *ErrorBuilder) Build() *Error

Build creates the final Error.

func (*ErrorBuilder) Code added in v0.8.0

func (e *ErrorBuilder) Code(c Code) *ErrorBuilder

Code sets the error code.

func (*ErrorBuilder) Detail added in v0.8.0

func (e *ErrorBuilder) Detail(key string, value any) *ErrorBuilder

Detail adds a key-value detail to the error.

func (*ErrorBuilder) Details added in v0.8.0

func (e *ErrorBuilder) Details(details map[string]any) *ErrorBuilder

Details adds multiple key-value details to the error.

func (*ErrorBuilder) Message added in v0.8.0

func (e *ErrorBuilder) Message(m string) *ErrorBuilder

Message sets the error message.

func (*ErrorBuilder) Messagef added in v0.8.0

func (e *ErrorBuilder) Messagef(format string, args ...any) *ErrorBuilder

Messagef sets the error message with formatting.

func (*ErrorBuilder) WithField added in v0.8.0

func (e *ErrorBuilder) WithField(field string, reason any) *ErrorBuilder

WithField is an alias for Detail, providing a more intuitive name for validation errors.

type ErrorCollector added in v0.8.0

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

ErrorCollector helps collect multiple validation errors.

func NewErrorCollector added in v0.8.0

func NewErrorCollector() *ErrorCollector

NewErrorCollector creates a new ErrorCollector.

func (*ErrorCollector) Add added in v0.8.0

func (c *ErrorCollector) Add(field, message string)

Add adds an error for a field.

func (*ErrorCollector) Addf added in v0.8.0

func (c *ErrorCollector) Addf(field, format string, args ...any)

Addf adds a formatted error for a field.

func (*ErrorCollector) AsError added in v0.8.0

func (c *ErrorCollector) AsError() *Error

AsError converts the collected errors into an Error. Returns nil if no errors have been collected.

func (*ErrorCollector) Clear added in v0.8.0

func (c *ErrorCollector) Clear()

Clear removes all collected errors.

func (*ErrorCollector) HasErrors added in v0.8.0

func (c *ErrorCollector) HasErrors() bool

HasErrors returns true if any errors have been collected.

type ErrorDetail added in v0.3.0

type ErrorDetail struct {
	Type  string `json:"type"`
	Value any    `json:"value"`
}

ErrorDetail represents a structured error detail.

type ErrorWithDetails added in v0.3.0

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

ErrorWithDetails extends Error with structured details.

func NewErrorWithDetails added in v0.3.0

func NewErrorWithDetails(code Code, message string, details ...*ErrorDetail) *ErrorWithDetails

NewErrorWithDetails creates a new error with details.

func (*ErrorWithDetails) AddAnyDetail added in v0.3.0

func (e *ErrorWithDetails) AddAnyDetail(msg proto.Message) *ErrorWithDetails

AddAnyDetail adds a protobuf Any detail.

func (*ErrorWithDetails) AddDetail added in v0.3.0

func (e *ErrorWithDetails) AddDetail(detail *ErrorDetail) *ErrorWithDetails

AddDetail adds a detail to the error.

func (*ErrorWithDetails) Code added in v0.3.0

func (e *ErrorWithDetails) Code() Code

Code returns the error code.

func (*ErrorWithDetails) Error added in v0.3.0

func (e *ErrorWithDetails) Error() string

Error implements the error interface.

func (*ErrorWithDetails) FormatForProtocol added in v0.3.0

func (e *ErrorWithDetails) FormatForProtocol(protocol string) any

FormatForProtocol formats error details for the specific protocol.

func (*ErrorWithDetails) GetDetails added in v0.3.0

func (e *ErrorWithDetails) GetDetails() []*ErrorDetail

GetDetails returns the error details.

func (*ErrorWithDetails) Message added in v0.3.0

func (e *ErrorWithDetails) Message() string

Message returns the error message.

func (*ErrorWithDetails) ToError added in v0.3.0

func (e *ErrorWithDetails) ToError(protocol string) *Error

ToError converts to regular Error with details.

type GRPCOption added in v0.6.0

type GRPCOption func(*grpcProtocol)

GRPCOption configures gRPC protocol

func WithGRPCReflection added in v0.6.0

func WithGRPCReflection(enable bool) GRPCOption

WithGRPCReflection enables/disables gRPC reflection

type GRPCSettings added in v0.6.0

type GRPCSettings struct {
	EnableReflection bool
}

GRPCSettings holds gRPC-specific settings

type GRPCWebSettings added in v0.6.0

type GRPCWebSettings struct{}

GRPCWebSettings holds gRPC-Web-specific settings

type GzipCompressor

type GzipCompressor struct{}

GzipCompressor implements gzip compression

func (*GzipCompressor) Compress

func (g *GzipCompressor) Compress(data []byte) ([]byte, error)

func (*GzipCompressor) Decompress

func (g *GzipCompressor) Decompress(data []byte) ([]byte, error)

func (*GzipCompressor) Name

func (g *GzipCompressor) Name() string

type Handler

type Handler[TIn, TOut any] func(context.Context, *TIn) (*TOut, error)

Handler represents a typed RPC handler function.

type HandlerCache

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

HandlerCache caches pre-computed handler information

type HandlerFunc

type HandlerFunc func(context.Context, any) (any, error)

HandlerFunc is the signature for RPC handlers.

type HandlerInfo

type HandlerInfo struct {
	HandlerValue reflect.Value
	HandlerType  reflect.Type
	InputType    reflect.Type
	OutputType   reflect.Type
	IsPointer    bool // Whether handler expects pointer input
}

HandlerInfo holds pre-computed handler information

func GetHandlerInfo

func GetHandlerInfo(handler any) (*HandlerInfo, error)

GetHandlerInfo returns cached handler information or computes it

type Interceptor

type Interceptor interface {
	// Intercept wraps the handler call.
	Intercept(ctx context.Context, method string, req any, handler func(context.Context, any) (any, error)) (any, error)
}

Interceptor is our own interceptor interface that works with dynamic types.

func ChainInterceptors

func ChainInterceptors(interceptors ...Interceptor) Interceptor

ChainInterceptors chains multiple interceptors into a single interceptor.

type JSONRPCError added in v0.4.0

type JSONRPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

JSONRPCError represents a JSON-RPC 2.0 error object

func NewJSONRPCError added in v0.4.0

func NewJSONRPCError(err *Error) *JSONRPCError

NewJSONRPCError creates a JSON-RPC error from a hyperway error

type JSONRPCOption added in v0.6.0

type JSONRPCOption func(*jsonrpcProtocol)

JSONRPCOption configures JSON-RPC protocol

func WithBatchLimit added in v0.6.0

func WithBatchLimit(limit int) JSONRPCOption

WithBatchLimit sets the batch request limit for JSON-RPC

type JSONRPCRequest added in v0.4.0

type JSONRPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
	ID      interface{}     `json:"id,omitempty"` // Can be string, number, or null
}

JSONRPCRequest represents a JSON-RPC 2.0 request

func (*JSONRPCRequest) IsNotification added in v0.4.0

func (r *JSONRPCRequest) IsNotification() bool

IsNotification returns true if this is a notification (no ID)

type JSONRPCResponse added in v0.4.0

type JSONRPCResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *JSONRPCError   `json:"error,omitempty"`
	ID      interface{}     `json:"id"` // Must match the request ID
}

JSONRPCResponse represents a JSON-RPC 2.0 response

type JSONRPCSettings added in v0.6.0

type JSONRPCSettings struct {
	Path       string
	BatchLimit int
}

JSONRPCSettings holds JSON-RPC-specific settings

type LoggingInterceptor

type LoggingInterceptor struct {
	Logger *log.Logger
}

LoggingInterceptor logs requests and responses.

func (*LoggingInterceptor) Intercept

func (l *LoggingInterceptor) Intercept(ctx context.Context, method string, req any, handler func(context.Context, any) (any, error)) (any, error)

type Method

type Method struct {
	Name       string
	Handler    any
	InputType  reflect.Type
	OutputType reflect.Type
	Options    MethodOptions
	StreamType StreamType // Type of streaming RPC

	// Protobuf type support - these are set if the types implement proto.Message
	ProtoInput  proto.Message // Optional: set if input type is a protobuf message
	ProtoOutput proto.Message // Optional: set if output type is a protobuf message
}

Method represents an RPC method.

type MethodBuilder

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

MethodBuilder provides a fluent API for building methods.

func (*MethodBuilder) Build

func (m *MethodBuilder) Build() *Method

Build returns the built method.

func (*MethodBuilder) In

func (m *MethodBuilder) In(example any) *MethodBuilder

In sets the input type.

func (*MethodBuilder) Out

func (m *MethodBuilder) Out(example any) *MethodBuilder

Out sets the output type.

func (*MethodBuilder) Validate

func (m *MethodBuilder) Validate(enabled bool) *MethodBuilder

Validate sets whether to validate input.

func (*MethodBuilder) WithDescription

func (m *MethodBuilder) WithDescription(description string) *MethodBuilder

WithDescription sets the method description for documentation.

func (*MethodBuilder) WithInterceptors

func (m *MethodBuilder) WithInterceptors(interceptors ...Interceptor) *MethodBuilder

WithInterceptors adds interceptors to the method.

type MethodChain added in v0.8.0

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

MethodChain provides a fluent API for building and registering methods.

func (*MethodChain) And added in v0.8.0

func (m *MethodChain) And(name string) *MethodChain

And allows chaining multiple method registrations.

func (*MethodChain) BidiStream added in v0.8.0

func (m *MethodChain) BidiStream(handler any) *MethodChain

BidiStream sets the handler for a bidirectional streaming RPC.

func (*MethodChain) Build added in v0.8.0

func (m *MethodChain) Build() *Method

Build returns the method without registering it. This is useful for batch registration.

func (*MethodChain) ClientStream added in v0.8.0

func (m *MethodChain) ClientStream(handler any) *MethodChain

ClientStream sets the handler for a client-streaming RPC.

func (*MethodChain) MustRegister added in v0.8.0

func (m *MethodChain) MustRegister() *MethodChain

MustRegister registers the method and panics on error.

func (*MethodChain) Register added in v0.8.0

func (m *MethodChain) Register() error

Register registers the method with the service.

func (*MethodChain) ServerStream added in v0.8.0

func (m *MethodChain) ServerStream(handler any) *MethodChain

ServerStream sets the handler for a server-streaming RPC.

func (*MethodChain) Unary added in v0.8.0

func (m *MethodChain) Unary(handler any) *MethodChain

Unary sets the handler for a unary RPC.

func (*MethodChain) Validate added in v0.8.0

func (m *MethodChain) Validate(enabled bool) *MethodChain

Validate enables or disables validation for this method.

func (*MethodChain) WithCompression added in v0.8.0

func (m *MethodChain) WithCompression(algorithm string) *MethodChain

WithCompression sets compression settings for this method.

func (*MethodChain) WithDescription added in v0.8.0

func (m *MethodChain) WithDescription(description string) *MethodChain

WithDescription sets a description for this method.

func (*MethodChain) WithInterceptors added in v0.8.0

func (m *MethodChain) WithInterceptors(interceptors ...Interceptor) *MethodChain

WithInterceptors adds interceptors to this method.

func (*MethodChain) WithMaxMessageSize added in v0.8.0

func (m *MethodChain) WithMaxMessageSize(size int) *MethodChain

WithMaxMessageSize sets the maximum message size for this method.

func (*MethodChain) WithRetry added in v0.8.0

func (m *MethodChain) WithRetry(maxAttempts int) *MethodChain

WithRetry sets retry configuration for this method.

func (*MethodChain) WithTimeout added in v0.8.0

func (m *MethodChain) WithTimeout(d time.Duration) *MethodChain

WithTimeout sets a timeout for this method.

type MethodConfig

type MethodConfig struct {
	// Name identifies the methods to which this configuration applies.
	Name []MethodName `json:"name"`

	// Timeout for the method. Format: "1s", "100ms", etc.
	Timeout string `json:"timeout,omitempty"`

	// RetryPolicy for the method.
	RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty"`
}

MethodConfig defines the configuration for specific methods.

type MethodDefinition added in v0.8.0

type MethodDefinition interface {
	// contains filtered or unexported methods
}

MethodDefinition represents a method that can be registered to a service.

func BidiStreamDef added in v0.8.0

func BidiStreamDef[TIn, TOut any](name string, handler func(context.Context, BidiStream[TIn, TOut]) error) MethodDefinition

BidiStreamDef creates a bidirectional streaming RPC method definition.

func ClientStreamDef added in v0.8.0

func ClientStreamDef[TIn, TOut any](name string, handler func(context.Context, ClientStream[TIn]) (*TOut, error)) MethodDefinition

ClientStreamDef creates a client-streaming RPC method definition.

func ServerStreamDef added in v0.8.0

func ServerStreamDef[TIn, TOut any](name string, handler func(context.Context, *TIn, ServerStream[TOut]) error) MethodDefinition

ServerStreamDef creates a server-streaming RPC method definition.

func Unary added in v0.8.0

func Unary[TIn, TOut any](name string, handler func(context.Context, *TIn) (*TOut, error)) MethodDefinition

Unary creates a unary RPC method definition.

type MethodGroup added in v0.8.0

type MethodGroup[TContext any] struct {
	// contains filtered or unexported fields
}

MethodGroup provides a way to register multiple methods with shared types.

func TypedGroup added in v0.8.0

func TypedGroup[TContext any](s *Service) *MethodGroup[TContext]

TypedGroup creates a new method group with a specific context type.

func (*MethodGroup[TContext]) Add added in v0.8.0

func (g *MethodGroup[TContext]) Add(method MethodDefinition) *MethodGroup[TContext]

Add adds a method to the group.

func (*MethodGroup[TContext]) MustRegister added in v0.8.0

func (g *MethodGroup[TContext]) MustRegister()

MustRegister registers all methods in the group and panics on error.

func (*MethodGroup[TContext]) Register added in v0.8.0

func (g *MethodGroup[TContext]) Register() error

Register registers all methods in the group.

type MethodName

type MethodName struct {
	// Service name including proto package name. Required.
	Service string `json:"service"`

	// Method name. If empty, applies to all methods in the service.
	Method string `json:"method,omitempty"`
}

MethodName identifies a gRPC method.

type MethodOptions

type MethodOptions struct {
	// Validate enables input validation for this method
	Validate *bool
	// Interceptors specific to this method
	Interceptors []Interceptor
	// Description is the method-level documentation
	Description string
}

MethodOptions configures a method.

type MetricsInterceptor

type MetricsInterceptor struct {
	RequestCount  int64
	SuccessCount  int64
	FailureCount  int64
	TotalDuration time.Duration
}

MetricsInterceptor collects metrics.

func (*MetricsInterceptor) Intercept

func (m *MetricsInterceptor) Intercept(ctx context.Context, method string, req any, handler func(context.Context, any) (any, error)) (any, error)

type Protocol added in v0.6.0

type Protocol interface {
	Name() string
	Config() ProtocolConfig
}

Protocol represents a supported RPC protocol

func Connect added in v0.6.0

func Connect(opts ...ConnectOption) Protocol

Connect creates a Connect protocol configuration

func GRPC added in v0.6.0

func GRPC(opts ...GRPCOption) Protocol

GRPC creates a gRPC protocol configuration

func GRPCWeb added in v0.6.0

func GRPCWeb() Protocol

GRPCWeb creates a gRPC-Web protocol configuration

func JSONRPC added in v0.6.0

func JSONRPC(path string, opts ...JSONRPCOption) Protocol

JSONRPC creates a JSON-RPC protocol configuration

type ProtocolConfig added in v0.6.0

type ProtocolConfig struct {
	Name     string
	Enabled  bool
	Settings interface{}
}

ProtocolConfig holds configuration for a specific protocol

type ProtocolConfigBuilder added in v0.8.0

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

ProtocolConfigBuilder provides a fluent API for configuring protocols.

func ConfigureProtocols added in v0.8.0

func ConfigureProtocols() *ProtocolConfigBuilder

ConfigureProtocols creates a new protocol configuration builder.

func (*ProtocolConfigBuilder) Build added in v0.8.0

Build creates a ServiceOption from the builder.

func (*ProtocolConfigBuilder) Connect added in v0.8.0

func (b *ProtocolConfigBuilder) Connect(allowJSON, allowProto bool) *ProtocolConfigBuilder

Connect configures Connect protocol.

func (*ProtocolConfigBuilder) GRPC added in v0.8.0

func (b *ProtocolConfigBuilder) GRPC(enableReflection bool) *ProtocolConfigBuilder

GRPC configures gRPC protocol.

func (*ProtocolConfigBuilder) GRPCWeb added in v0.8.0

GRPCWeb configures gRPC-Web protocol.

func (*ProtocolConfigBuilder) JSONRPC added in v0.8.0

func (b *ProtocolConfigBuilder) JSONRPC(path string, batchLimit int) *ProtocolConfigBuilder

JSONRPC configures JSON-RPC protocol.

type ProtocolPreset added in v0.8.0

type ProtocolPreset string

ProtocolPreset represents a predefined set of protocol configurations.

const (
	// PresetREST enables Connect and JSON-RPC protocols for REST-like APIs.
	PresetREST ProtocolPreset = "rest"

	// PresetGRPC enables gRPC and gRPC-Web protocols.
	PresetGRPC ProtocolPreset = "grpc"

	// PresetAll enables all available protocols.
	PresetAll ProtocolPreset = "all"

	// PresetMinimal enables only Connect protocol.
	PresetMinimal ProtocolPreset = "minimal"
)

type RecoveryInterceptor

type RecoveryInterceptor struct{}

RecoveryInterceptor recovers from panics.

func (*RecoveryInterceptor) Intercept

func (r *RecoveryInterceptor) Intercept(ctx context.Context, method string, req any, handler func(context.Context, any) (any, error)) (resp any, err error)

type RetryInterceptor

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

RetryInterceptor implements retry logic according to gRPC specification.

func DefaultRetryInterceptor

func DefaultRetryInterceptor() *RetryInterceptor

DefaultRetryInterceptor creates a retry interceptor with default retry policy.

func NewRetryInterceptor

func NewRetryInterceptor(config *ServiceConfig) *RetryInterceptor

NewRetryInterceptor creates a new retry interceptor with the given service config.

func (*RetryInterceptor) Intercept

func (r *RetryInterceptor) Intercept(
	ctx context.Context,
	method string,
	req any,
	handler func(context.Context, any) (any, error),
) (any, error)

Intercept implements the Interceptor interface with retry logic.

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is the maximum number of attempts including the original request.
	// Must be greater than 1. Required.
	MaxAttempts int `json:"maxAttempts"`

	// InitialBackoff is the initial delay before the first retry.
	// Format: "0.1s", "100ms", etc.
	InitialBackoff string `json:"initialBackoff"`

	// MaxBackoff is the maximum delay between retries.
	// Format: "30s", "1m", etc.
	MaxBackoff string `json:"maxBackoff"`

	// BackoffMultiplier is the multiplier for exponential backoff.
	// Default: 2.0
	BackoffMultiplier float64 `json:"backoffMultiplier"`

	// RetryableStatusCodes defines which status codes should trigger a retry.
	// Common values: ["UNAVAILABLE"], ["DEADLINE_EXCEEDED"], ["UNAVAILABLE", "RESOURCE_EXHAUSTED"]
	RetryableStatusCodes []string `json:"retryableStatusCodes"`
}

RetryPolicy defines the retry configuration for a method according to gRPC spec.

func AggressiveRetryPolicy

func AggressiveRetryPolicy() *RetryPolicy

AggressiveRetryPolicy returns a more aggressive retry policy for critical operations.

func DefaultRetryPolicy

func DefaultRetryPolicy() *RetryPolicy

DefaultRetryPolicy returns a sensible default retry policy.

type RetryThrottling

type RetryThrottling struct {
	// MaxTokens is the maximum number of tokens in the bucket.
	// Must be in range (0, 1000]. Required.
	MaxTokens int `json:"maxTokens"`

	// TokenRatio is the ratio of tokens to add on each successful RPC.
	// Must be greater than 0. Decimal places beyond 3 are ignored.
	TokenRatio float64 `json:"tokenRatio"`
}

RetryThrottling controls client-side retry throttling.

type ServerStream added in v0.3.0

type ServerStream[T any] interface {
	// Send sends a message to the client.
	Send(*T) error
	// Context returns the context for this stream.
	Context() context.Context
}

ServerStream represents a server-side stream.

type ServerStreamHandler added in v0.3.0

type ServerStreamHandler[TIn, TOut any] func(context.Context, *TIn, ServerStream[TOut]) error

ServerStreamHandler handles server-streaming RPCs.

type Service

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

Service represents an RPC service.

func NewService

func NewService(name string, opts ...ServiceOption) *Service

NewService creates a new RPC service.

func (*Service) AutoRegister added in v0.8.0

func (s *Service) AutoRegister(service any) error

AutoRegister attempts to automatically register methods from a struct. This is experimental and uses reflection to find methods with appropriate signatures.

func (*Service) ExportAllProtos

func (s *Service) ExportAllProtos() (map[string]string, error)

ExportAllProtos exports all proto files including dependencies.

func (*Service) ExportAllProtosWithOptions added in v0.5.0

func (s *Service) ExportAllProtosWithOptions(options ...hyperproto.ExportOption) (map[string]string, error)

ExportAllProtosWithOptions exports all proto files including dependencies with language-specific options.

func (*Service) ExportProto

func (s *Service) ExportProto() (string, error)

ExportProto exports the service definition as a .proto file.

func (*Service) ExportProtoWithOptions added in v0.5.0

func (s *Service) ExportProtoWithOptions(options ...hyperproto.ExportOption) (string, error)

ExportProtoWithOptions exports the service definition as a .proto file with language-specific options.

func (*Service) GetFileDescriptorSet

func (s *Service) GetFileDescriptorSet() *descriptorpb.FileDescriptorSet

GetFileDescriptorSet returns the FileDescriptorSet for this service.

func (*Service) Group added in v0.8.0

func (s *Service) Group() *MethodGroup[any]

Group creates a new method group for registering methods with shared context type.

func (*Service) Handlers

func (s *Service) Handlers() map[string]http.Handler

Handlers returns the HTTP handlers for all methods.

func (*Service) JSONRPCHandler added in v0.4.0

func (s *Service) JSONRPCHandler() http.Handler

JSONRPCHandler returns an HTTP handler for JSON-RPC requests. This handler processes all JSON-RPC requests at a single endpoint.

func (*Service) Method added in v0.8.0

func (s *Service) Method(name string) *MethodChain

Method creates a new method chain for the service.

func (*Service) MustRegister

func (s *Service) MustRegister(method *Method)

MustRegister is like Register but panics on error.

func (*Service) MustRegisterAll added in v0.8.0

func (s *Service) MustRegisterAll(methods ...MethodDefinition)

MustRegisterAll registers multiple methods to the service and panics on error.

func (*Service) MustRegisterService added in v0.8.0

func (s *Service) MustRegisterService(registrar ServiceRegistrar)

MustRegisterService registers all methods from a ServiceRegistrar and panics on error.

func (*Service) Name

func (s *Service) Name() string

Name returns the service name.

func (*Service) PackageName

func (s *Service) PackageName() string

PackageName returns the service package name.

func (*Service) Register

func (s *Service) Register(method *Method) error

Register adds a method to the service.

func (*Service) RegisterAll added in v0.8.0

func (s *Service) RegisterAll(methods ...MethodDefinition) error

RegisterAll registers multiple methods to the service.

func (*Service) RegisterService added in v0.8.0

func (s *Service) RegisterService(registrar ServiceRegistrar) error

RegisterService registers all methods from a ServiceRegistrar.

func (*Service) RegisterStreamingMethod added in v0.3.0

func (s *Service) RegisterStreamingMethod(method *Method) error

RegisterStreamingMethod adds a streaming method to the service

type ServiceConfig

type ServiceConfig struct {
	// MethodConfig contains per-method configuration.
	MethodConfig []MethodConfig `json:"methodConfig,omitempty"`

	// RetryThrottling controls client-side retry throttling.
	RetryThrottling *RetryThrottling `json:"retryThrottling,omitempty"`
}

ServiceConfig represents the complete service configuration.

func ParseServiceConfig

func ParseServiceConfig(jsonConfig string) (*ServiceConfig, error)

ParseServiceConfig parses a JSON service configuration.

type ServiceOption

type ServiceOption func(*ServiceOptions)

ServiceOption configures a service.

func DisableConnect added in v0.8.0

func DisableConnect() ServiceOption

DisableConnect disables Connect protocol.

func DisableGRPC added in v0.8.0

func DisableGRPC() ServiceOption

DisableGRPC disables gRPC protocol.

func DisableGRPCWeb added in v0.8.0

func DisableGRPCWeb() ServiceOption

DisableGRPCWeb disables gRPC-Web protocol.

func DisableJSONRPC added in v0.8.0

func DisableJSONRPC() ServiceOption

DisableJSONRPC disables JSON-RPC protocol.

func EnableAllProtocols added in v0.8.0

func EnableAllProtocols() ServiceOption

EnableAllProtocols is a convenience function that enables all protocols with default settings.

func EnableGRPCProtocols added in v0.8.0

func EnableGRPCProtocols() ServiceOption

EnableGRPCProtocols enables gRPC-related protocols.

func EnableRESTProtocols added in v0.8.0

func EnableRESTProtocols() ServiceOption

EnableRESTProtocols enables protocols suitable for REST-like APIs.

func WithConnect added in v0.8.0

func WithConnect(allowJSON, allowProto bool) ServiceOption

WithConnect enables Connect protocol with specified settings.

func WithDescription

func WithDescription(description string) ServiceOption

WithDescription sets the service description for documentation.

func WithEdition

func WithEdition(edition string) ServiceOption

WithEdition enables Protobuf Editions mode with the specified edition.

func WithGRPC added in v0.8.0

func WithGRPC(enableReflection bool) ServiceOption

WithGRPC enables gRPC protocol with optional reflection.

func WithGRPCWeb added in v0.8.0

func WithGRPCWeb() ServiceOption

WithGRPCWeb enables gRPC-Web protocol.

func WithInterceptors

func WithInterceptors(interceptors ...Interceptor) ServiceOption

WithInterceptors adds interceptors to the service.

func WithJSONRPC added in v0.4.0

func WithJSONRPC(path string, batchLimit int) ServiceOption

WithJSONRPC enables JSON-RPC protocol with specified settings.

func WithMaxReceiveMessageSize added in v0.5.0

func WithMaxReceiveMessageSize(size int) ServiceOption

WithMaxReceiveMessageSize sets the maximum size of a message that can be received. Default is 4MB to match gRPC defaults.

func WithMaxSendMessageSize added in v0.5.0

func WithMaxSendMessageSize(size int) ServiceOption

WithMaxSendMessageSize sets the maximum size of a message that can be sent. Default is 4MB to match gRPC defaults.

func WithPackage

func WithPackage(pkg string) ServiceOption

WithPackage sets the protobuf package name.

func WithPreset added in v0.8.0

func WithPreset(preset ProtocolPreset) ServiceOption

WithPreset applies a predefined set of protocol configurations.

func WithReflection

func WithReflection(enabled bool) ServiceOption

WithReflection enables gRPC reflection.

func WithServiceConfig

func WithServiceConfig(jsonConfig string) ServiceOption

WithServiceConfig sets the gRPC service configuration.

func WithValidation

func WithValidation(enabled bool) ServiceOption

WithValidation enables validation by default.

type ServiceOptions

type ServiceOptions struct {
	// Package sets the protobuf package name
	Package string
	// EnableValidation enables input validation by default
	EnableValidation bool
	// EnableReflection enables gRPC reflection
	EnableReflection bool
	// Interceptors to apply to all methods
	Interceptors []Interceptor
	// Edition sets the Protobuf edition (e.g., "2023", "2024")
	Edition string
	// UseEditions enables Protobuf Editions mode instead of proto3
	UseEditions bool
	// ServiceConfig is the gRPC service configuration (JSON string)
	ServiceConfig string
	// Description is the service-level documentation
	Description string
	// EnabledProtocols specifies which protocols are enabled for this service
	EnabledProtocols map[string]ProtocolConfig
	// MaxReceiveMessageSize is the maximum size of a message that can be received (default: 4MB)
	MaxReceiveMessageSize int
	// MaxSendMessageSize is the maximum size of a message that can be sent (default: 4MB)
	MaxSendMessageSize int
}

ServiceOptions configures a service.

type ServiceRegistrar added in v0.8.0

type ServiceRegistrar interface {
	RegisterMethods(*Service) error
}

ServiceRegistrar provides an interface for services that can self-register.

type StreamProtocol added in v0.7.0

type StreamProtocol interface {
	// ReadFrame reads a single frame from the stream
	// Returns: data, compressed, isEndOfStream, error
	ReadFrame(r io.Reader, maxMessageSize int) ([]byte, bool, bool, error)

	// WriteFrame writes a single frame to the stream
	WriteFrame(w io.Writer, data []byte, compressed bool) error

	// WriteEndOfStream writes an end-of-stream marker (if applicable)
	WriteEndOfStream(w io.Writer) error

	// SetStreamHeaders sets protocol-specific headers for streaming
	SetStreamHeaders(h http.Header, contentType, compressionType string)

	// SetResponseHeaders sets protocol-specific headers for unary responses
	SetResponseHeaders(h http.Header, compressed bool, compressionType string)

	// FormatError formats an error for the protocol
	FormatError(err *Error) []byte

	// ParseError parses an error from protocol-specific format
	ParseError(data []byte) *Error

	// SupportsTrailers returns true if the protocol uses HTTP trailers for errors
	SupportsTrailers() bool
}

StreamProtocol defines the interface for protocol-specific streaming operations

type StreamType added in v0.3.0

type StreamType int

StreamType defines the type of streaming RPC.

const (
	// StreamTypeUnary is a unary RPC (no streaming).
	StreamTypeUnary StreamType = iota
	// StreamTypeServerStream is a server-streaming RPC.
	StreamTypeServerStream
	// StreamTypeClientStream is a client-streaming RPC.
	StreamTypeClientStream
	// StreamTypeBidiStream is a bidirectional streaming RPC.
	StreamTypeBidiStream
)

type TimeoutInterceptor

type TimeoutInterceptor struct {
	Timeout time.Duration
}

TimeoutInterceptor adds timeout to requests.

func (*TimeoutInterceptor) Intercept

func (t *TimeoutInterceptor) Intercept(ctx context.Context, method string, req any, handler func(context.Context, any) (any, error)) (any, error)

type ZstdCompressor added in v0.5.0

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

ZstdCompressor implements Zstandard compression

func NewZstdCompressor added in v0.5.0

func NewZstdCompressor() (*ZstdCompressor, error)

NewZstdCompressor creates a new Zstandard compressor

func (*ZstdCompressor) Compress added in v0.5.0

func (z *ZstdCompressor) Compress(data []byte) ([]byte, error)

func (*ZstdCompressor) Decompress added in v0.5.0

func (z *ZstdCompressor) Decompress(data []byte) ([]byte, error)

func (*ZstdCompressor) Name added in v0.5.0

func (z *ZstdCompressor) Name() string

Jump to

Keyboard shortcuts

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