grpcserver

package
v1.28.0 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2025 License: MIT Imports: 15 Imported by: 0

README

grpcserver

GoDoc Widget

A gRPC server implementation with YAML/JSON based configuration, built-in interceptors, and observability features.

Features

  • Configuration: Flexible gRPC server setup with configuration from YAML/JSON files
  • Interceptors: Built-in interceptors for observability and reliability
  • Metrics: Prometheus metrics collection

Usage

package main

import (
    "github.com/acronis/go-appkit/config"
    "github.com/acronis/go-appkit/grpcserver"
    "github.com/acronis/go-appkit/log"
    "github.com/acronis/go-appkit/service"
)

func main () {
    // Load configuration from YAML/JSON file
    cfgLoader := config.NewDefaultLoader("my_service")
    cfg := &AppConfig{
        Server: grpcserver.NewConfig(),
        Log:    log.NewConfig(),
    }
    err := cfgLoader.LoadFromFile("config.yml", config.DataTypeYAML, cfg)

    // Create logger from config
    logger, loggerClose := log.NewLogger(cfg.Log)
    defer loggerClose()

    // Create gRPC server with configuration
    grpcServer, err := grpcserver.New(cfg.Server, logger)
    if err != nil {
        return err
    }

    // Register your services
    pb.RegisterYourServiceServer(grpcServer.GRPCServer, &yourService{})

    // Start server using service micro-framework
    service.New(logger, grpcServer).Start()
}

Documentation

Configuration

The server can be easily configured from JSON/YAML files with options including:

  • Network address and port
  • TLS configuration
  • Timeout settings
  • Graceful shutdown parameters

See the examples directory for complete configuration examples.

Documentation

Overview

Package grpcserver provides a gRPC server implementation with built-in interceptors for logging, metrics, recovery, and request ID handling. The server supports TLS, keepalive configuration, and graceful shutdown.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Address        string          `mapstructure:"address" yaml:"address" json:"address"`
	UnixSocketPath string          `mapstructure:"unixSocketPath" yaml:"unixSocketPath" json:"unixSocketPath"`
	Timeouts       TimeoutsConfig  `mapstructure:"timeouts" yaml:"timeouts" json:"timeouts"`
	Keepalive      KeepaliveConfig `mapstructure:"keepalive" yaml:"keepalive" json:"keepalive"`
	Limits         LimitsConfig    `mapstructure:"limits" yaml:"limits" json:"limits"`
	Log            LogConfig       `mapstructure:"log" yaml:"log" json:"log"`
	TLS            TLSConfig       `mapstructure:"tls" yaml:"tls" json:"tls"`
	// contains filtered or unexported fields
}

Config represents a set of configuration parameters for gRPC Server. Configuration can be loaded in different formats (YAML, JSON) using config.Loader, viper, or with json.Unmarshal/yaml.Unmarshal functions directly.

func NewConfig

func NewConfig(options ...ConfigOption) *Config

NewConfig creates a new instance of the Config.

func NewDefaultConfig

func NewDefaultConfig(options ...ConfigOption) *Config

NewDefaultConfig creates a new instance of the Config with default values.

func (*Config) KeyPrefix

func (c *Config) KeyPrefix() string

KeyPrefix returns a key prefix with which all configuration parameters should be presented. Implements config.KeyPrefixProvider interface.

func (*Config) Set

func (c *Config) Set(dp config.DataProvider) error

Set sets gRPC Server configuration values from config.DataProvider.

func (*Config) SetProviderDefaults

func (c *Config) SetProviderDefaults(dp config.DataProvider)

SetProviderDefaults sets default configuration values for gRPC Server in config.DataProvider. Implements config.Config interface.

type ConfigOption

type ConfigOption func(*configOptions)

ConfigOption is a type for functional options for the Config.

func WithKeyPrefix

func WithKeyPrefix(keyPrefix string) ConfigOption

WithKeyPrefix returns a ConfigOption that sets a key prefix for parsing configuration parameters. This prefix will be used by config.Loader.

type GRPCServer

type GRPCServer struct {
	GRPCServer *grpc.Server
	Logger     log.FieldLogger
	// contains filtered or unexported fields
}

GRPCServer represents a wrapper around grpc.Server with additional fields and methods. It also implements service.Unit and service.MetricsRegisterer interfaces.

func New

func New(cfg *Config, logger log.FieldLogger, options ...Option) (*GRPCServer, error)

New creates a new GRPCServer with predefined logging, metrics collecting, recovering after panics and request ID functionality.

func (*GRPCServer) Address

func (s *GRPCServer) Address() string

Address returns the current address the server is bound to. This may change after starting the server if the original address was :0.

func (*GRPCServer) MustRegisterMetrics

func (s *GRPCServer) MustRegisterMetrics()

MustRegisterMetrics registers metrics in Prometheus client and panics if any error occurs.

func (*GRPCServer) Start

func (s *GRPCServer) Start(fatalError chan<- error)

Start starts the gRPC server in a blocking way. It's supposed that this method will be called in a separate goroutine. If a fatal error occurs, it will be sent to the fatalError channel.

func (*GRPCServer) Stop

func (s *GRPCServer) Stop(gracefully bool) error

Stop stops the gRPC server gracefully or forcefully based on the gracefully parameter. If gracefully is true, it waits for ongoing calls to finish within the shutdown timeout. If gracefully is false, it immediately terminates all connections.

func (*GRPCServer) UnregisterMetrics

func (s *GRPCServer) UnregisterMetrics()

UnregisterMetrics unregisters metrics in Prometheus client.

type KeepaliveConfig

type KeepaliveConfig struct {
	Time    config.TimeDuration `mapstructure:"time" yaml:"time" json:"time"`
	Timeout config.TimeDuration `mapstructure:"timeout" yaml:"timeout" json:"timeout"`
	MinTime config.TimeDuration `mapstructure:"minTime" yaml:"minTime" json:"minTime"`
}

KeepaliveConfig represents a set of configuration parameters for gRPC Server relating to keepalive.

func (*KeepaliveConfig) Set

Set sets keepalive server configuration values from config.DataProvider. Implements config.Config interface.

type LimitsConfig

type LimitsConfig struct {
	// MaxConcurrentStreams is the maximum number of concurrent streams per connection.
	MaxConcurrentStreams uint32 `mapstructure:"maxConcurrentStreams" yaml:"maxConcurrentStreams" json:"maxConcurrentStreams"`

	// MaxRecvMessageSize is the maximum size of a received message in bytes.
	MaxRecvMessageSize config.ByteSize `mapstructure:"maxRecvMessageSize" yaml:"maxRecvMessageSize" json:"maxRecvMessageSize"`

	// MaxSendMessageSize is the maximum size of a sent message in bytes.
	MaxSendMessageSize config.ByteSize `mapstructure:"maxSendMessageSize" yaml:"maxSendMessageSize" json:"maxSendMessageSize"`
}

LimitsConfig represents a set of configuration parameters for gRPC Server relating to limits.

func (*LimitsConfig) Set

Set sets limit server configuration values from config.DataProvider.

type LogConfig

type LogConfig struct {
	CallStart          bool                `mapstructure:"callStart" yaml:"callStart" json:"callStart"`
	ExcludedMethods    []string            `mapstructure:"excludedMethods" yaml:"excludedMethods" json:"excludedMethods"`
	SlowCallThreshold  config.TimeDuration `mapstructure:"slowCallThreshold" yaml:"slowCallThreshold" json:"slowCallThreshold"`
	TimeSlotsThreshold config.TimeDuration `mapstructure:"timeSlotsThreshold" yaml:"timeSlotsThreshold" json:"timeSlotsThreshold"`
}

LogConfig represents a set of configuration parameters for gRPC Server relating to logging.

func (*LogConfig) Set

func (l *LogConfig) Set(dp config.DataProvider) error

Set sets log server configuration values from config.DataProvider.

type LoggingOptions

type LoggingOptions struct {
	UnaryCustomLoggerProvider  func(ctx context.Context, info *grpc.UnaryServerInfo) log.FieldLogger
	StreamCustomLoggerProvider func(ctx context.Context, info *grpc.StreamServerInfo) log.FieldLogger
}

LoggingOptions represents options for gRPC request logging that used in GRPCServer.

type MetricsOptions

type MetricsOptions struct {
	Namespace                   string
	DurationBuckets             []float64
	ConstLabels                 prometheus.Labels
	UnaryUserAgentTypeProvider  func(ctx context.Context, info *grpc.UnaryServerInfo) string
	StreamUserAgentTypeProvider func(ctx context.Context, info *grpc.StreamServerInfo) string
}

MetricsOptions represents options for gRPC request metrics that used in GRPCServer.

type Option

type Option func(*serverOptions)

Option represents a functional option for configuring GRPCServer.

func WithLoggingOptions

func WithLoggingOptions(opts LoggingOptions) Option

WithLoggingOptions configures gRPC request logging.

func WithMetricsOptions

func WithMetricsOptions(opts MetricsOptions) Option

WithMetricsOptions configures gRPC request metrics.

func WithStreamInterceptors

func WithStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) Option

WithStreamInterceptors adds stream interceptors to the server.

func WithUnaryInterceptors

func WithUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) Option

WithUnaryInterceptors adds unary interceptors to the server.

type TLSConfig

type TLSConfig struct {
	Enabled     bool   `mapstructure:"enabled" yaml:"enabled" json:"enabled"`
	Certificate string `mapstructure:"cert" yaml:"cert" json:"cert"`
	Key         string `mapstructure:"key" yaml:"key" json:"key"`
}

TLSConfig contains configuration parameters needed to initialize(or not) secure server

func (*TLSConfig) Set

func (s *TLSConfig) Set(dp config.DataProvider) error

Set sets security server configuration values from config.DataProvider.

type TimeoutsConfig

type TimeoutsConfig struct {
	Shutdown config.TimeDuration `mapstructure:"shutdown" yaml:"shutdown" json:"shutdown"`
}

TimeoutsConfig represents a set of configuration parameters for gRPC Server relating to timeouts.

func (*TimeoutsConfig) Set

Set sets timeout server configuration values from config.DataProvider. Implements config.Config interface.

Directories

Path Synopsis
Package interceptor provides gRPC interceptors for logging, metrics collection, panic recovery, and request ID handling.
Package interceptor provides gRPC interceptors for logging, metrics collection, panic recovery, and request ID handling.
throttle
Package throttle provides configurable gRPC interceptors for rate limiting and in-flight request limiting.
Package throttle provides configurable gRPC interceptors for rate limiting and in-flight request limiting.

Jump to

Keyboard shortcuts

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