rpc

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 11 Imported by: 3

Documentation

Index

Constants

View Source
const (
	CodeInvalidArgument    = "INVALID_ARGUMENT"
	CodeUnauthenticated    = "UNAUTHENTICATED"
	CodeForbidden          = "FORBIDDEN"
	CodeNotFound           = "NOT_FOUND"
	CodeConflict           = "CONFLICT"
	CodeFailedPrecondition = "FAILED_PRECONDITION"
	CodeRateLimited        = "RATE_LIMITED"
	CodeUnavailable        = "UNAVAILABLE"
	CodeDeadlineExceeded   = "DEADLINE_EXCEEDED"
	CodeCanceled           = "CANCELED"
	CodeInternal           = "INTERNAL"
	CodeOutcomeUnknown     = "OUTCOME_UNKNOWN"
)

Public error codes are stable transport classifications, not execution policy.

View Source
const (
	HandlerKindExecute = "execute"
	HandlerKindQuery   = "query"
)

Variables

This section is empty.

Functions

func Resolver

func Resolver(server *Server) command.Resolver

Resolver returns a command.Resolver that registers endpoint providers into this server.

Types

type Endpoint

type Endpoint struct {
	Method       string        `json:"method"`
	MessageType  string        `json:"messageType"`
	HandlerKind  string        `json:"handlerKind"`
	RequestType  *TypeRef      `json:"requestType,omitempty"`
	ResponseType *TypeRef      `json:"responseType,omitempty"`
	Timeout      time.Duration `json:"timeout"`
	Streaming    bool          `json:"streaming"`
	Idempotent   bool          `json:"idempotent"`
	Permissions  []string      `json:"permissions,omitempty"`
	Roles        []string      `json:"roles,omitempty"`
	Summary      string        `json:"summary,omitempty"`
	Description  string        `json:"description,omitempty"`
	Tags         []string      `json:"tags,omitempty"`
	Deprecated   bool          `json:"deprecated,omitempty"`
	Since        string        `json:"since,omitempty"`
}

Endpoint describes a registered RPC method.

type EndpointDefinition

type EndpointDefinition interface {
	Spec() EndpointSpec
	NewRequest() any
	RequestType() reflect.Type
	ResponseType() reflect.Type
	Invoke(context.Context, any) (any, error)
}

EndpointDefinition is the explicit endpoint contract registered in the RPC server.

func NewEndpoint

func NewEndpoint[Req any, Res any](
	spec EndpointSpec,
	handler func(context.Context, RequestEnvelope[Req]) (ResponseEnvelope[Res], error),
) EndpointDefinition

NewEndpoint builds an explicit typed endpoint definition.

type EndpointSpec

type EndpointSpec struct {
	Method      string
	MessageType string
	Kind        MethodKind
	Timeout     time.Duration
	Streaming   bool
	Idempotent  bool
	Permissions []string
	Roles       []string
	Summary     string
	Description string
	Tags        []string
	Deprecated  bool
	Since       string
}

EndpointSpec declares endpoint metadata independent from handler implementation details.

type EndpointsProvider

type EndpointsProvider interface {
	RPCEndpoints() []EndpointDefinition
}

EndpointsProvider can expose one or more endpoint definitions for resolver registration.

type Error

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

Error is a transport-friendly error envelope.

func DefaultErrorMapper added in v0.25.0

func DefaultErrorMapper(_ context.Context, err error) (public *Error)

DefaultErrorMapper returns fixed public classifications without copying source messages, arbitrary text codes, validation values, metadata or retry hints. Context causes take precedence, then the nearest structured error after known runner wrappers. Only the canonical text codes below are recognized; custom application codes/details require an explicit host ErrorMapper. Cancellation/deadline do not prove rollback, and unknown outcome is explicit.

func MapError added in v0.25.0

func MapError(ctx context.Context, err error, mapper ErrorMapper) *Error

MapError applies a host mapper, falling back to DefaultErrorMapper when nil or declined. A nil error returns nil without invoking the host. Transports opt in explicitly; Server.Invoke and handler-created envelopes are unchanged. The returned envelope and top-level details map are fresh; nested host details remain host-owned and must be immutable or independently allocated per call.

type ErrorMapper added in v0.25.0

type ErrorMapper func(context.Context, error) *Error

ErrorMapper explicitly projects a Go error into a public error. Returning nil declines the mapping. Implementations must use controlled public messages and allowlisted, JSON-safe details; error text and diagnostic metadata are not safe by default. A mapper must not mutate err or shared details during a call. Retryable is informational and never authorizes automatic mutation replay.

type FailureEvent

type FailureEvent struct {
	Stage  FailureStage
	Method string
	Err    error
	Panic  any
}

FailureEvent carries context for strategy/logging decisions.

type FailureLogger

type FailureLogger func(FailureEvent)

FailureLogger receives failure events when configured.

type FailureMode

type FailureMode int

FailureMode controls how the server reacts to registration/invocation failures.

const (
	// FailureModeReject returns registration errors and re-panics invoke panics.
	FailureModeReject FailureMode = iota
	// FailureModeRecover returns registration errors and converts invoke panics to errors.
	FailureModeRecover
	// FailureModeLogAndContinue suppresses failures after logging them.
	// For register, the endpoint is skipped. For invoke panic, call returns an error.
	FailureModeLogAndContinue
)

type FailureStage

type FailureStage string

FailureStage identifies where a failure happened.

const (
	FailureStageRegister FailureStage = "register"
	FailureStageInvoke   FailureStage = "invoke"
)

type FailureStrategy

type FailureStrategy func(FailureEvent) FailureMode

FailureStrategy decides how to handle a failure event.

type InvokeHandler added in v0.16.1

type InvokeHandler func(context.Context, InvokeRequest) (any, error)

InvokeHandler executes one RPC invoke step in a middleware chain.

type InvokeRequest added in v0.16.1

type InvokeRequest struct {
	Method   string
	Endpoint Endpoint
	Payload  any
}

InvokeRequest carries method metadata and payload through middleware.

type MethodKind

type MethodKind string

MethodKind describes endpoint invocation shape.

const (
	MethodKindCommand MethodKind = HandlerKindExecute
	MethodKindQuery   MethodKind = HandlerKindQuery
)

type Middleware added in v0.16.1

type Middleware func(next InvokeHandler) InvokeHandler

Middleware wraps invoke execution with cross-cutting behavior.

type Option

type Option func(*Server)

Option customizes server behavior.

func WithFailureLogger

func WithFailureLogger(logger FailureLogger) Option

WithFailureLogger sets an optional callback for failure events.

func WithFailureMode

func WithFailureMode(mode FailureMode) Option

WithFailureMode sets a fixed strategy mode.

func WithFailureStrategy

func WithFailureStrategy(strategy FailureStrategy) Option

WithFailureStrategy sets a custom failure strategy function.

func WithMiddleware added in v0.16.1

func WithMiddleware(mw ...Middleware) Option

WithMiddleware appends invoke middleware in registration order.

type RequestEnvelope

type RequestEnvelope[T any] struct {
	Data T           `json:"data"`
	Meta RequestMeta `json:"meta,omitempty"`
}

RequestEnvelope is the canonical method request shape for transport adapters.

type RequestMeta

type RequestMeta struct {
	ActorID       string              `json:"actorId,omitempty"`
	Roles         []string            `json:"roles,omitempty"`
	Tenant        string              `json:"tenant,omitempty"`
	RequestID     string              `json:"requestId,omitempty"`
	CorrelationID string              `json:"correlationId,omitempty"`
	Permissions   []string            `json:"permissions,omitempty"`
	Scope         map[string]any      `json:"scope,omitempty"`
	Headers       map[string]string   `json:"headers,omitempty"`
	Params        map[string]string   `json:"params,omitempty"`
	Query         map[string][]string `json:"query,omitempty"`
}

RequestMeta carries method-agnostic execution metadata.

type ResponseEnvelope

type ResponseEnvelope[T any] struct {
	Data  T      `json:"data,omitempty"`
	Error *Error `json:"error,omitempty"`
}

ResponseEnvelope is the canonical method response shape for transport adapters.

type Server

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

Server provides a lightweight in memory RPC method registry and invoker. Transport adapters can use this server to register and invoke command/query handlers.

func NewServer

func NewServer(opts ...Option) *Server

NewServer creates an empty RPC server registry.

func (*Server) Endpoint

func (s *Server) Endpoint(method string) (Endpoint, bool)

Endpoint returns endpoint metadata for the method.

func (*Server) EndpointMeta

func (s *Server) EndpointMeta(method string) (Endpoint, bool)

EndpointMeta returns enriched endpoint metadata for the method.

func (*Server) Endpoints

func (s *Server) Endpoints() []Endpoint

Endpoints returns all endpoint metadata sorted by method.

func (*Server) EndpointsMeta

func (s *Server) EndpointsMeta() []Endpoint

EndpointsMeta returns enriched metadata for all endpoints sorted by method.

func (*Server) Invoke

func (s *Server) Invoke(ctx context.Context, method string, payload any) (any, error)

Invoke executes a registered RPC method using the provided payload. payload should already be transport-decoded into the expected message type.

func (*Server) NewMessageForMethod

func (s *Server) NewMessageForMethod(method string) (any, error)

NewMessageForMethod creates a zero-value message instance for transport decoding.

func (*Server) NewRequestForMethod

func (s *Server) NewRequestForMethod(method string) (any, error)

NewRequestForMethod creates a zero-value request envelope instance for transport decoding.

func (*Server) RegisterEndpoint

func (s *Server) RegisterEndpoint(def EndpointDefinition) error

RegisterEndpoint stores an explicit endpoint definition.

func (*Server) RegisterEndpoints

func (s *Server) RegisterEndpoints(defs ...EndpointDefinition) error

RegisterEndpoints stores explicit endpoint definitions in registration order.

type TypeRef

type TypeRef struct {
	GoType  string `json:"goType"`
	PkgPath string `json:"pkgPath,omitempty"`
	Name    string `json:"name,omitempty"`
	Kind    string `json:"kind,omitempty"`
	Pointer bool   `json:"pointer,omitempty"`
}

TypeRef describes a Go type in endpoint metadata for codegen/doc discovery.

Jump to

Keyboard shortcuts

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