grpc

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: MIT Imports: 11 Imported by: 0

README

Compogo gRPC 🔌

Compogo gRPC — это production-ready gRPC-сервер для Compogo, построенный поверх стандартной библиотеки google.golang.org/grpc. Полностью интегрируется с жизненным циклом Compogo, поддерживает тонкую настройку через флаги и graceful shutdown из коробки.

🚀 Установка

go get github.com/Compogo/grpc
📦 Быстрый старт
package main

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/runner"
    "github.com/Compogo/grpc"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithOsSignalCloser(),
        runner.WithRunner(),
        grpc.Component,  // добавляем gRPC-сервер
        compogo.WithComponents(
            userServiceComponent,
        ),
    )

    if err := app.Serve(); err != nil {
        panic(err)
    }
}

// Компонент с бизнес-логикой
var userServiceComponent = &component.Component{
    Dependencies: component.Components{grpc.Component},
    Init: component.StepFunc(func(c container.Container) error {
        return c.Provide(NewUserService)
    }),
    PreExecute: component.StepFunc(func(c container.Container) error {
        return c.Invoke(func(server *grpc.Server, svc *UserService) {
            // Регистрируем сервис ДО запуска сервера
            pb.RegisterUserServiceServer(server.GetGRPC(), svc)
        })
    }),
}
✨ Возможности
🎯 Production-ready конфигурация

Сервер настраивается через флаги — всё, что нужно для продакшена:

./myapp \
    --server.grpc.interface=0.0.0.0 \
    --server.grpc.port=9090 \
    --server.grpc.max_concurrent_streams=1000 \
    --server.grpc.min_time=1s \
    --server.grpc.permit_without_stream=true \
    --server.grpc.keepalive.time=10s \
    --server.grpc.keepalive.timeout=20s
🔄 Жизненный цикл
Init         → создаём конфиг и сервер
BindFlags    → добавляем флаги
Configuration→ применяем конфиг
PreExecute   → РЕГИСТРИРУЕМ СЕРВИСЫ (важно!)
Execute      → запускаем сервер через Runner
Stop         → graceful shutdown (GracefulStop)

Критический момент: сервисы должны регистрироваться в PreExecute — ДО того, как сервер запустится в Execute.

🔌 Доступ к чистому grpc.Server
server.GetGRPC()  // для регистрации сервисов
🧩 Пример с несколькими сервисами
var GrpcServicesComponent = &component.Component{
    Dependencies: component.Components{grpc.Component},
    Init: component.StepFunc(func(c container.Container) error {
        return c.Provides(
            NewUserService,
            NewOrderService,
            NewProductService,
        )
    }),
    PreExecute: component.StepFunc(func(c container.Container) error {
        return c.Invoke(func(
            server *grpc.Server,
            users *UserService,
            orders *OrderService,
            products *ProductService,
        ) {
            pb.RegisterUserServiceServer(server.GetGRPC(), users)
            pb.RegisterOrderServiceServer(server.GetGRPC(), orders)
            pb.RegisterProductServiceServer(server.GetGRPC(), products)
        })
    }),
}

Documentation

Index

Constants

View Source
const (
	MaxConcurrentStreamsFieldName = "server.grpc.max_concurrent_streams"
	MinTimeFieldName              = "server.grpc.min_time"
	PermitWithoutStreamFieldName  = "server.grpc.permit_without_stream"
	KeepaliveTimeFieldName        = "server.grpc.keepalive.time"
	KeepaliveTimeoutFieldName     = "server.grpc.keepalive.timeout"
	InterfaceFieldName            = "server.grpc.interface"
	PortFieldName                 = "server.grpc.port"

	MaxConcurrentStreamsDefault = uint32(1000)
	MinTimeDefault              = time.Second
	PermitWithoutStreamDefault  = true
	KeepaliveTimeDefault        = time.Second * 10
	KeepaliveTimeoutDefault     = time.Second * 20
	InterfaceDefault            = "0.0.0.0"
	PortDefault                 = uint16(9090)
)

Variables

View Source
var Component = &component.Component{
	Dependencies: component.Components{
		runner.Component,
	},
	Init: component.StepFunc(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewServer,
		)
	}),
	BindFlags: component.BindFlags(func(flagSet flag.FlagSet, container container.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.BoolVar(&config.PermitWithoutStream, PermitWithoutStreamFieldName, PermitWithoutStreamDefault, "")
			flagSet.Uint16Var(&config.Port, PortFieldName, PortDefault, "")
			flagSet.Uint32Var(&config.MaxConcurrentStreams, MaxConcurrentStreamsFieldName, MaxConcurrentStreamsDefault, "")
			flagSet.StringVar(&config.Interface, InterfaceFieldName, InterfaceDefault, "")
			flagSet.DurationVar(&config.MinTime, MinTimeFieldName, MinTimeDefault, "")
			flagSet.DurationVar(&config.KeepaliveTime, KeepaliveTimeFieldName, KeepaliveTimeDefault, "")
			flagSet.DurationVar(&config.KeepaliveTimeout, KeepaliveTimeoutFieldName, KeepaliveTimeoutDefault, "")
		})
	}),
	Configuration: component.StepFunc(func(container container.Container) error {
		return container.Invoke(Configuration)
	}),
	Execute: component.StepFunc(func(container container.Container) error {
		return container.Invoke(func(r runner.Runner, server *Server) error {
			return r.RunProcess(server)
		})
	}),
	Stop: component.StepFunc(func(container container.Container) error {
		return container.Invoke(func(server *Server) error {
			return server.Close()
		})
	}),
}

Component is a ready-to-use Compogo component that provides a gRPC server. It automatically:

  • Registers Config and Server in the DI container
  • Adds command-line flags for server configuration
  • Configures the server during Configuration phase
  • Starts the server as a runner task during Execute phase
  • Performs graceful shutdown during Stop phase

Usage:

compogo.WithComponents(
    runner.Component,
    grpc.Component,
    // ... your service components
)

Service registration should happen in PreExecute phase:

var userServiceComponent = &component.Component{
    Dependencies: []*component.Component{grpc.Component},
    PreExecute: component.StepFunc(func(c container.Container) error {
        return c.Invoke(func(server *grpc.Server, svc *UserService) {
            pb.RegisterUserServiceServer(server.GetGRPC(), svc)
        })
    }),
}

Functions

This section is empty.

Types

type Config

type Config struct {
	PermitWithoutStream  bool
	Port                 uint16
	MaxConcurrentStreams uint32
	Interface            string
	MinTime              time.Duration
	KeepaliveTime        time.Duration
	KeepaliveTimeout     time.Duration
}

func Configuration

func Configuration(config *Config, configurator configurator.Configurator) *Config

Configuration applies configuration values to the Config struct. It reads from the provided configurator and sets defaults if values are not present. This function is designed to be used with container.Invoke in the Configuration phase.

func NewConfig

func NewConfig() *Config

type Server

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

Server wraps a gRPC server with Compogo lifecycle support. It implements runner.Process and io.Closer for seamless integration with the application's lifecycle.

func NewServer

func NewServer(config *Config) *Server

NewServer creates a new gRPC server with the given configuration. The server is pre-configured with production-ready defaults:

  • Max concurrent streams limit
  • Keepalive enforcement policy
  • Keepalive parameters

All settings can be overridden via command-line flags.

func (*Server) Close

func (server *Server) Close() error

Close implements io.Closer for graceful shutdown. It calls GracefulStop on the underlying gRPC server, allowing in-flight requests to complete before shutting down.

func (*Server) GetGRPC

func (server *Server) GetGRPC() *grpc.Server

GetGRPC returns the underlying *grpc.Server. This is used to register service implementations before starting the server.

Example:

pb.RegisterUserServiceServer(server.GetGRPC(), &userServiceImpl{})

func (*Server) Name added in v0.0.5

func (server *Server) Name() string

func (*Server) Process

func (server *Server) Process(_ context.Context) error

Process implements runner.Process. It starts the gRPC server and blocks until the server stops or an error occurs. The server is automatically stopped when the provided context is canceled.

The method:

  • Creates a TCP listener on the configured interface and port
  • Starts the gRPC server
  • Closes the listener when the context is done
  • Returns nil on normal shutdown, error on failure

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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