grpc

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 15 Imported by: 2

Documentation

Overview

Package grpc contains code generation logic to produce a server that serves gRPC requests and a client that encode requests to and decode responses from a gRPC server. It produces gRPC service definitions (.proto files) from Loom expressions that were created by executing a design DSL. It then compiles the definition using the protocol buffer compiler (protoc) using the Go gRPC plugin, and generates code that hooks up the compiled protocol buffer types and gRPC code with the types and code generated by Loom. It uses the "proto3" syntax to generate gRPC service and protocol buffer message definitions.

In addition to the code generation logic, the grpc package contains:

  • A customizable server and client handler interface to handle unary and streaming RPCs.
  • Encoder and decoder interfaces to convert a protocol buffer type to a Loom type and vice versa.
  • Error handlers to encode and decode error responses.
  • Interceptors (a.k.a middlewares) to wrap additional functionality around unary and streaming RPCs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeError

func DecodeError(err error) proto.Message

DecodeError returns the error message encoded in the status details if error is a gRPC status error. It returns the first status detail that can be decoded as a protocol buffer message, skipping details that grpc-go could not decode. It returns nil if the error is not a gRPC status error or if no protocol buffer detail is found.

func EncodeError

func EncodeError(err error) error

EncodeError returns a gRPC status error from the given error with the error response encoded in the status details. If error is a Loom ServiceError type it implements a heuristic to compute the status code from the Timeout, Fault, and Temporary characteristics of the ServiceError. If error is not a ServiceError or a gRPC status error it returns a gRPC status error with Unknown code and Fault characteristic set.

func EncodeServerError added in v1.8.0

func EncodeServerError(err error, mapper ErrorMapper) error

EncodeServerError converts an endpoint error to a gRPC status. Designed mappings take precedence over Loom's general status conversion.

func ErrInvalidType

func ErrInvalidType(svc, m, expected string, actual any) error

ErrInvalidType is the error returned when the wrong type is given to a encoder or decoder.

func NewErrorResponse

func NewErrorResponse(err error) *loompb.ErrorResponse

NewErrorResponse creates a new ErrorResponse protocol buffer message from the given error. If the given error is a Loom ServiceError, the ErrorResponse message will be set with the corresponding Timeout, Temporary, and Fault characteristics. If the error is not a Loom ServiceError, it creates an ErrorResponse message with the Fault field set to true.

func NewProtoValue added in v1.4.0

func NewProtoValue(value any) (*structpb.Value, error)

NewProtoValue converts a Go value into its google.protobuf.Value form. It returns a descriptive error when the value is not representable by google.protobuf.Value.

func NewServiceError

func NewServiceError(resp *loompb.ErrorResponse) *loom.ServiceError

NewServiceError returns a Loom ServiceError type for the given ErrorResponse message.

func NewStatusError

func NewStatusError(code codes.Code, err error, details ...protoiface.MessageV1) error

NewStatusError creates a gRPC status error with the error response messages added to its details. A codes.OK code is replaced with codes.Unknown: a status with code OK yields a nil error, which would silently swallow err.

func ObserveStreamDecodeError added in v1.8.0

func ObserveStreamDecodeError(ctx context.Context, err error) error

ObserveStreamDecodeError classifies a failed gRPC stream receive or request conversion. End-of-stream is a clean completion and is not classified as a failure.

func ObserveStreamEncodeError added in v1.8.0

func ObserveStreamEncodeError(ctx context.Context, err error) error

ObserveStreamEncodeError classifies an error that prevented a typed stream response from being converted to its protocol buffer representation.

func ObserveStreamWriteError added in v1.8.0

func ObserveStreamWriteError(ctx context.Context, err error) error

ObserveStreamWriteError classifies a failed gRPC stream send and emits the corresponding stream failure event.

func ServeStream added in v1.8.0

func ServeStream(ctx context.Context, spec StreamServerSpec) error

ServeStream executes one streaming gRPC request and owns its context, status, observation, and clean completion lifecycle.

func ServeUnary added in v1.8.0

func ServeUnary(ctx context.Context, request any, spec UnaryServerSpec) (any, error)

ServeUnary executes one unary gRPC request and owns its context, status, metadata, and observation lifecycle.

func ValidateResponseContract added in v1.8.0

func ValidateResponseContract(observation *ResponseContractObservation, contract ResponseContractCase) error

ValidateResponseContract validates transport-owned gRPC wire invariants.

Types

type ClientError

type ClientError struct {
	// Name is a name for this class of errors.
	Name string
	// Message contains the specific error details.
	Message string
	// Service is the name of the service.
	Service string
	// Method is the name of the service method.
	Method string
	// Is the error temporary?
	Temporary bool
	// Is the error a timeout?
	Timeout bool
	// Is the error a server-side fault?
	Fault bool
}

ClientError is an error returned by a gRPC service client.

func (*ClientError) Error

func (c *ClientError) Error() string

Error builds an error message.

type ErrorMapper added in v1.8.0

type ErrorMapper func(string, error) (ErrorMapping, bool, error)

ErrorMapper maps a typed service error to its designed gRPC contract. The boolean result reports whether the error has a designed mapping.

type ErrorMapping added in v1.8.0

type ErrorMapping struct {
	// Code is the gRPC status code for the designed error.
	Code codes.Code
	// Detail is the designed protocol buffer error detail.
	Detail protoiface.MessageV1
}

ErrorMapping describes a designed gRPC status and detail message.

type Invoker

type Invoker interface {
	Invoke(ctx context.Context, req any) (res any, err error)
}

Invoker invokes a gRPC method. The request and response types are Loom types.

func NewInvoker

func NewInvoker(fn RemoteFunc, enc RequestEncoder, dec ResponseDecoder) Invoker

NewInvoker returns an invoker to invoke gRPC methods.

type RemoteFunc

type RemoteFunc func(ctx context.Context, reqpb any, opts ...grpc.CallOption) (respb any, err error)

RemoteFunc invokes a RPC method.

type RequestDecoder

type RequestDecoder func(ctx context.Context, pb any, md metadata.MD) (v any, err error)

RequestDecoder is used by the server to decode gRPC request message type and any incoming metadata to a Loom value.

type RequestEncoder

type RequestEncoder func(ctx context.Context, v any, md *metadata.MD) (pb any, err error)

RequestEncoder is used by the client to encode a Loom value to a gRPC message type and sets the outgoing metadata.

type ResponseContractCase added in v1.8.0

type ResponseContractCase struct {
	// ID is stable while the service contract is unchanged.
	ID string
	// Kind identifies a successful result or service error.
	Kind ResponseContractCaseKind
	// StatusCode is the declared gRPC status code.
	StatusCode codes.Code
	// MessageType is the protobuf full name of a successful response message.
	MessageType string
	// ErrorName is the declared service error name.
	ErrorName string
	// DetailType is the protobuf full name of the expected status detail.
	DetailType string
	// RequiredHeaders lists required response metadata keys.
	RequiredHeaders []string
	// RequiredTrailers lists required trailer metadata keys.
	RequiredTrailers []string
	// Stream describes a supported streaming completion contract.
	Stream *StreamingResponseContract
}

ResponseContractCase describes one generated gRPC wire-response branch.

type ResponseContractCaseKind added in v1.8.0

type ResponseContractCaseKind string

ResponseContractCaseKind identifies a successful result or service error.

const (
	// ResponseContractSuccess identifies a successful response contract case.
	ResponseContractSuccess ResponseContractCaseKind = "success"
	// ResponseContractError identifies an error response contract case.
	ResponseContractError ResponseContractCaseKind = "error"
)

type ResponseContractObservation added in v1.8.0

type ResponseContractObservation struct {
	// Message is the unary response message.
	Message proto.Message
	// Error is the unary call error.
	Error error
	// Headers contains response header metadata.
	Headers metadata.MD
	// Trailers contains response trailer metadata.
	Trailers metadata.MD
	// Messages contains server-stream messages in receive order.
	Messages []proto.Message
	// TerminalError is the final server-stream receive error.
	TerminalError error
}

ResponseContractObservation contains values observed through a generated gRPC client. Unary scenarios set Message and Error. Streaming scenarios set Messages and TerminalError.

type ResponseDecoder

type ResponseDecoder func(ctx context.Context, pb any, hdr, trlr metadata.MD) (v any, err error)

ResponseDecoder is used by the client to decode gRPC response message type and any incoming metadata (headers and trailers) to a Loom value.

type ResponseEncoder

type ResponseEncoder func(ctx context.Context, v any, hdr, trlr *metadata.MD) (pb any, err error)

ResponseEncoder is used by the server to encode a Loom value to a gRPC response message type and sets the response headers and trailers.

type StreamHandler

type StreamHandler interface {
	// Handle handles a streaming RPC.
	//
	// input contains the endpoint payload (if any) and generated
	// endpoint stream.
	Handle(ctx context.Context, input any) (err error)
	// Decode decodes the protocol buffer message and metadata to
	// the service type. For client-side and bidirectional streams,
	// the message is nil.
	Decode(ctx context.Context, reqpb any) (req any, err error)
}

StreamHandler handles a streaming RPC. The stream may be client-side, server-side, or bidirectional.

func NewStreamHandler

func NewStreamHandler(e loom.Endpoint, dec RequestDecoder) StreamHandler

NewStreamHandler returns a handler to handle streaming gRPC endpoints.

type StreamServerSpec added in v1.8.0

type StreamServerSpec struct {
	// Service is the Loom service name.
	Service string
	// Method is the Loom method name.
	Method string
	// Decode creates the typed endpoint stream input.
	Decode func(context.Context) (any, error)
	// Handle invokes the typed streaming endpoint.
	Handle func(context.Context, any) error
	// MapError maps designed service errors to gRPC status contracts.
	MapError ErrorMapper
}

StreamServerSpec describes one generated streaming gRPC method adapter.

type StreamingResponseContract added in v1.8.0

type StreamingResponseContract struct {
	// Direction is the designed stream direction.
	Direction string
	// Terminal identifies the expected completion behavior.
	Terminal string
}

StreamingResponseContract describes a selected gRPC stream completion.

type UnaryHandler

type UnaryHandler interface {
	// Handle handles a unary RPC.
	//
	// It takes a protocol buffer message type and returns a
	// protocol buffer message type and any error when executing the
	// RPC.
	Handle(ctx context.Context, reqpb any) (respb any, err error)
}

UnaryHandler handles a unary RPC. The request and response types are protocol buffer message types.

func NewUnaryHandler

func NewUnaryHandler(e loom.Endpoint, dec RequestDecoder, enc ResponseEncoder) UnaryHandler

NewUnaryHandler returns a handler to handle unary gRPC endpoints.

type UnaryServerSpec added in v1.8.0

type UnaryServerSpec struct {
	// Service is the Loom service name.
	Service string
	// Method is the Loom method name.
	Method string
	// Handler decodes, invokes, and encodes the typed endpoint.
	Handler UnaryHandler
	// MapError maps designed service errors to gRPC status contracts.
	MapError ErrorMapper
}

UnaryServerSpec describes one generated unary gRPC method adapter.

Directories

Path Synopsis
Package codegen generates gRPC servers, clients, and .proto definitions from an evaluated Loom design.
Package codegen generates gRPC servers, clients, and .proto definitions from an evaluated Loom design.
Package middleware contains gRPC server and client interceptors that wraps unary and streaming RPCs to provide additional functionality.
Package middleware contains gRPC server and client interceptors that wraps unary and streaming RPCs to provide additional functionality.
otel
Package otel provides thin OpenTelemetry helpers for Loom gRPC servers and clients.
Package otel provides thin OpenTelemetry helpers for Loom gRPC servers and clients.
Package loompb contains protocol buffer message types used by the code generation logic.
Package loompb contains protocol buffer message types used by the code generation logic.

Jump to

Keyboard shortcuts

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