rpc

package
v0.27.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 21 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"
)
View Source
const (
	IssueDefinitionRequired    = "definition_required"
	IssueMethodRequired        = "method_required"
	IssueMethodInvalid         = "method_invalid"
	IssueRequestTypeRequired   = "request_type_required"
	IssueResponseTypeRequired  = "response_type_required"
	IssueRequestFactoryInvalid = "request_factory_invalid"
	IssueResponseShapeInvalid  = "response_shape_invalid"
	IssueHandlerRequired       = "handler_required"
	IssueEndpointUnverifiable  = "endpoint_unverifiable"
	IssueValidationPanicked    = "validation_panicked"
	IssueValidationMalformed   = "validation_malformed"
	IssueDuplicateMethod       = "duplicate_method"
	IssueDefinitionChanged     = "definition_changed"
	IssueServerRequired        = "server_required"
)

Stable issue codes are independent of human-readable messages.

View Source
const ContractSchemaVersion = "rpc-contract/v1"

ContractSchemaVersion identifies the wire format, independently of package releases.

View Source
const MaxSafeInteger int64 = 9007199254740991

Variables

This section is empty.

Functions

func DecodeContractJSON added in v0.26.0

func DecodeContractJSON[T any](m *ContractManifest, schema WireSchema, data []byte) (T, error)

DecodeContractJSON decodes original input into a fresh public DTO using Go's ordinary encoding/json semantics, then validates the resulting value. Unknown fields remain ignored; aliases and duplicate objects follow the typed decoder. Decode or validation failure returns the zero T, never a partially valid DTO. Callers must pair T with the schema exported from that public type.

func Resolver

func Resolver(server *Server) command.Resolver

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

func ValidateContractJSON added in v0.26.0

func ValidateContractJSON(m *ContractManifest, schema WireSchema, data []byte) error

ValidateContractJSON checks a canonical serialized JSON value, with exact numeric bounds. It rejects duplicate keys and noncanonical struct-field aliases. This is not a typed Go decoder: use DecodeContractJSON for incoming DTOs and ValidateContractValue for typed output. Exporting alone changes no runtime.

func ValidateContractValue added in v0.26.0

func ValidateContractValue(m *ContractManifest, schema WireSchema, value any) error

ValidateContractValue checks a declared public DTO before execution or egress. It validates both its actual JSON representation and numeric values that tags such as omitempty/omitzero could hide. Custom wire encoders are checked through their declared serialized representation; their internal state is not a DTO.

Types

type CommandContract added in v0.26.0

type CommandContract struct {
	ID          string
	Input       reflect.Type
	Result      reflect.Type // nil means receipt-only; inline execution need not return a result.
	Summary     string
	Description string
}

CommandContract is an optional public declaration. It does not register a handler, change RPCCommand, or use ExposeInAdmin as an export/permission gate.

func CommandContractFor added in v0.26.0

func CommandContractFor[Input, Result any](id string) CommandContract

func DescribeCommandContract added in v0.26.0

func DescribeCommandContract(p CommandContractProvider) (CommandContract, error)

DescribeCommandContract uses explicit declaration metadata first, then RPCOptions, then RPCDescription. Conflicting identities are errors. Methods that construct handlers are never called.

type CommandContractProvider added in v0.26.0

type CommandContractProvider interface{ RPCCommandContract() CommandContract }

type ContractManifest added in v0.26.0

type ContractManifest struct {
	SchemaVersion string                          `json:"schemaVersion"`
	Definitions   map[string]WireSchema           `json:"definitions"`
	Endpoints     map[string]EndpointContract     `json:"endpoints"`
	Commands      map[string]NamedCommandContract `json:"commands"`
	Canonical     map[string]WireSchema           `json:"canonical"`
	Fingerprint   string                          `json:"fingerprint,omitempty"`
}

func ExportContracts added in v0.26.0

func ExportContracts(opts ExportOptions) (*ContractManifest, error)

ExportContracts is offline: no handler invocation, discovery or service startup.

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 EndpointContract added in v0.26.0

type EndpointContract struct {
	Request  WireSchema `json:"request"`
	Response WireSchema `json:"response"`
}

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 EndpointValidation added in v0.26.1

type EndpointValidation struct {
	Method string            `json:"method"`
	Status ValidationStatus  `json:"status"`
	Issues []ValidationIssue `json:"issues,omitempty"`
}

EndpointValidation is the result for one method. Unverifiable is not valid.

func ValidateEndpoint added in v0.26.1

func ValidateEndpoint(def EndpointDefinition) EndpointValidation

ValidateEndpoint inspects metadata and optional validation evidence without calling NewRequest or Invoke. Panicking custom metadata/validators are reported as unverifiable using a safe message, without exposing the panic value.

type EndpointValidationError added in v0.26.1

type EndpointValidationError struct{ Validation EndpointValidation }

EndpointValidationError is returned for strict structural validation failures, unless the configured registration failure strategy suppresses it.

func (*EndpointValidationError) Error added in v0.26.1

func (e *EndpointValidationError) Error() string

type EndpointValidator added in v0.26.1

type EndpointValidator interface{ ValidateEndpoint() []ValidationIssue }

EndpointValidator is an optional, side-effect-free structural attestation. Implementations must not invoke handlers or factories. A nil issue list attests that the definition's handler, types and request factory are structurally valid. The framework cannot prove the truth of an arbitrary custom implementation.

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 ExportOptions added in v0.26.0

type ExportOptions struct {
	Endpoints []EndpointDefinition
	Commands  []CommandContract
	Bounds    map[reflect.Type]IntegerBounds
	Enums     map[reflect.Type][]string
	Overrides map[reflect.Type]WireSchema
}

ExportOptions is explicit selection and wire policy. Bounds are an enforceable contract: adapters decode input with DecodeContractJSON and validate typed output with ValidateContractValue before serialization. Unbounded wide numeric integers fail export. Overrides apply only to custom marshalers/interfaces, never to ordinary numeric fields.

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 IntegerBounds added in v0.26.0

type IntegerBounds struct{ Minimum, Maximum int64 }

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 NamedCommandContract added in v0.26.0

type NamedCommandContract struct {
	Input       WireSchema  `json:"input"`
	Result      *WireSchema `json:"result,omitempty"`
	ResultMode  string      `json:"resultMode"`
	Summary     string      `json:"summary,omitempty"`
	Description string      `json:"description,omitempty"`
}

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.

func WithStrictValidation added in v0.26.1

func WithStrictValidation() Option

WithStrictValidation rejects invalid or unverifiable endpoints before publication. It preserves failure strategies; always check ValidateEndpoints at startup when LogAndContinue may suppress registration errors.

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.

func (*Server) ValidateEndpoints added in v0.26.1

func (s *Server) ValidateEndpoints() ValidationReport

ValidateEndpoints reports current structural evidence without changing the registry. Custom validators run outside server locks and must be side-effect free.

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.

type ValidationIssue added in v0.26.1

type ValidationIssue struct {
	Method  string           `json:"method"`
	Code    string           `json:"code"`
	Status  ValidationStatus `json:"status"`
	Message string           `json:"message"`
}

ValidationIssue describes one bounded structural check, not authorization.

type ValidationReport added in v0.26.1

type ValidationReport struct {
	Ready              bool                 `json:"ready"`
	Endpoints          []EndpointValidation `json:"endpoints"`
	RegistrationIssues []ValidationIssue    `json:"registrationIssues,omitempty"`
}

ValidationReport includes registered endpoints and sticky strict-registration failures. A new server is needed to clear failed startup attempts.

type ValidationStatus added in v0.26.1

type ValidationStatus string

ValidationStatus distinguishes structural validity from unavailable evidence.

const (
	ValidationValid        ValidationStatus = "valid"
	ValidationInvalid      ValidationStatus = "invalid"
	ValidationUnverifiable ValidationStatus = "unverifiable"
)

type WireProperty added in v0.26.0

type WireProperty struct {
	Schema   WireSchema `json:"schema"`
	Required bool       `json:"required"`
}

type WireSchema added in v0.26.0

type WireSchema struct {
	Kind       string                  `json:"kind"`
	Ref        string                  `json:"ref,omitempty"`
	Nullable   bool                    `json:"nullable,omitempty"`
	Properties map[string]WireProperty `json:"properties,omitempty"`
	Element    *WireSchema             `json:"element,omitempty"`
	Values     []string                `json:"values,omitempty"`
	Variants   []WireSchema            `json:"variants,omitempty"`
	Encoding   string                  `json:"encoding,omitempty"`
	Minimum    *int64                  `json:"minimum,omitempty"`
	Maximum    *int64                  `json:"maximum,omitempty"`
	Length     *int                    `json:"length,omitempty"`
}

WireSchema describes JSON, not Go validation requirements. Required properties describe serialization presence; Nullable independently permits JSON null.

Jump to

Keyboard shortcuts

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