gserver

package
v0.40.416 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 50 Imported by: 3 modules, 8 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gserver implements a combined gRPC, gRPC-Web and REST server that listens on one or more URLs and multiplexes all three protocols on each listener.

A Server is created with Start from a Config, a dig dependency container and a map of ServiceFactory functions. Each factory builds a Service; a Service that also implements RouteRegistrator gets its REST routes registered, and one that implements GRPCRegistrator gets its gRPC services registered. Plain HTTP/1.1 traffic is routed to the REST router, HTTP/2 "application/grpc" traffic to the gRPC server, and "application/grpc-web+proto" / "application/grpc-web-text" requests are translated to gRPC and their trailers are encoded into the gRPC-Web response body.

Every request passes through a fixed middleware chain: rate limiting (optional), correlation ID, CORS (optional), identity extraction (roles.IdentityProvider built from Config.IdentityMap), metrics, request logging, authorization (restserver/authz built from Config.Authz), and a readiness check. gRPC calls go through the equivalent interceptor chain, prefixed by a panic-recovery interceptor and NewRequestValidationUnaryInterceptor.

Minimal usage:

cfg := &gserver.Config{
	ListenURLs: []string{"https://0.0.0.0:8443"},
	Services:   []string{"status"},
	ServerTLS: &gserver.TLSInfo{
		CertFile: "server.pem",
		KeyFile:  "server-key.pem",
	},
}
factories := map[string]gserver.ServiceFactory{
	"status": func(s gserver.GServer) any {
		return func() error { s.AddService(newStatusService(s)); return nil }
	},
}
srv, err := gserver.Start("api", cfg, container, factories)
if err != nil {
	return err
}
defer srv.Close()
<-srv.Err() // or wait for a signal

The container must provide discovery.Discovery and, when Config.IdentityMap enables JWT or DPoP authentication, a jwt.Parser. Config is typically loaded from YAML; see the yaml tags on Config for the field names.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// WarnUnaryRequestLatency is the duration above which a gRPC request
	// (unary or stream) is logged at WARNING level as slow_request. It is a
	// process-global setting read on every request.
	WarnUnaryRequestLatency = 2 * time.Second
)

Functions

func NewRequestValidationUnaryInterceptor added in v0.35.366

func NewRequestValidationUnaryInterceptor() grpc.UnaryServerInterceptor

NewRequestValidationUnaryInterceptor returns a unary interceptor that calls Validate on requests implementing Validator and rejects the call with the returned error. It is always installed by Start.

Types

type CORS

type CORS struct {
	// Enabled specifies if the CORS is enabled.
	Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`

	// MaxAge indicates how long (in seconds) the results of a preflight request can be cached.
	MaxAge int `json:"max_age,omitempty" yaml:"max_age,omitempty"`

	// AllowedOrigins is a list of origins a cross-domain request can be executed from.
	AllowedOrigins []string `json:"allowed_origins,omitempty" yaml:"allowed_origins,omitempty"`

	// AllowedMethods is a list of methods the client is allowed to use with cross-domain requests.
	AllowedMethods []string `json:"allowed_methods,omitempty" yaml:"allowed_methods,omitempty"`

	// AllowedHeaders is list of non simple headers the client is allowed to use with cross-domain requests.
	AllowedHeaders []string `json:"allowed_headers,omitempty" yaml:"allowed_headers,omitempty"`

	// ExposedHeaders indicates which headers are safe to expose to the API of a CORS API specification.
	ExposedHeaders []string `json:"exposed_headers,omitempty" yaml:"exposed_headers,omitempty"`

	// AllowCredentials indicates whether the request can include user credentials.
	AllowCredentials *bool `json:"allow_credentials,omitempty" yaml:"allow_credentials,omitempty"`

	// OptionsPassthrough instructs preflight to let other potential next handlers to process the OPTIONS method.
	OptionsPassthrough *bool `json:"options_pass_through,omitempty" yaml:"options_pass_through,omitempty"`

	// Debug flag adds additional output to debug server side CORS issues.
	Debug *bool `json:"debug,omitempty" yaml:"debug,omitempty"`
}

CORS configures cross-origin handling. When enabled the REST handler is wrapped with github.com/rs/cors; AllowedOrigins, ExposedHeaders and AllowCredentials are also applied to gRPC-Web responses on TLS listeners.

func (*CORS) GetAllowCredentials

func (c *CORS) GetAllowCredentials() bool

GetAllowCredentials returns the AllowCredentials flag; safe on a nil receiver.

func (*CORS) GetDebug

func (c *CORS) GetDebug() bool

GetDebug returns the Debug flag; safe on a nil receiver.

func (*CORS) GetEnabled

func (c *CORS) GetEnabled() bool

GetEnabled returns true when CORS is configured and enabled; safe on a nil receiver.

func (*CORS) GetOptionsPassthrough

func (c *CORS) GetOptionsPassthrough() bool

GetOptionsPassthrough returns the OptionsPassthrough flag; safe on a nil receiver.

type Config

type Config struct {
	// DebugLogs enables verbose per-request debug logging in the gRPC/HTTP mux.
	DebugLogs bool `json:"debug_logs" yaml:"debug_logs"`

	// Description provides description of the server
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// Disabled specifies if the service is disabled
	Disabled bool `json:"disabled,omitempty" yaml:"disabled,omitempty"`

	// ClientURL is the public URL exposed to clients
	ClientURL string `json:"client_url" yaml:"client_url"`

	// ListenURLs is the list of URLs to listen on. Supported schemes are
	// http, https, unix and unixs; a URL without scheme defaults to https when
	// ServerTLS is set. URLs with the same address share one listener.
	ListenURLs []string `json:"listen_urls" yaml:"listen_urls"`

	// ServerTLS provides the TLS config for the server; required for https/unixs URLs.
	ServerTLS *TLSInfo `json:"server_tls,omitempty" yaml:"server_tls,omitempty"`

	// SkipLogPaths if set, specifies a list of paths to not log.
	// this can be used for /v1/status/node or /metrics
	SkipLogPaths []telemetry.LoggerSkipPath `json:"logger_skip_paths,omitempty" yaml:"logger_skip_paths,omitempty"`

	// PromGrpc adds the go-grpc-prometheus unary and stream interceptors.
	PromGrpc bool `json:"prom_grpc" yaml:"prom_grpc"`

	// Services is the list of service names to enable; each must have a
	// ServiceFactory registered in the map passed to Start.
	Services []string `json:"services" yaml:"services"`

	// IdentityMap configures how callers are authenticated and mapped to roles
	// (see gserver/roles). When nil an empty map is used and all callers are guests.
	IdentityMap *roles.IdentityMap `json:"identity_map" yaml:"identity_map"`

	// Authz configures path/role based authorization (see restserver/authz).
	// It is only activated when at least one of Allow, AllowAny or AllowAnyRole is set.
	Authz *authz.Config `json:"authz" yaml:"authz"`

	// CORS contains configuration for CORS.
	CORS *CORS `json:"cors,omitempty" yaml:"cors,omitempty"`

	// RateLimit contains configuration for the rate limiter
	RateLimit *RateLimit `json:"rate_limit,omitempty" yaml:"rate_limit,omitempty"`

	// Timeout settings
	Timeout struct {
		// Request is how long Close waits for in-flight requests to finish
		// before forcing shutdown; default 3s.
		Request time.Duration `json:"request,omitempty" yaml:"request,omitempty"`
	} `json:"timeout" yaml:"timeout"`

	// KeepAlive settings
	KeepAlive KeepAliveCfg `json:"keep_alive" yaml:"keep_alive"`

	// MaxRecvMsgSize sets the maximum gRPC message size a client can send;
	// the MaxRecvMsgSize Option takes precedence when set.
	MaxRecvMsgSize int `json:"max_recv_msg_size,omitempty" yaml:"max_recv_msg_size,omitempty"`

	// MaxSendMsgSize sets the maximum gRPC message size the server can send;
	// the MaxSendMsgSize Option takes precedence when set.
	MaxSendMsgSize int `json:"max_send_msg_size,omitempty" yaml:"max_send_msg_size,omitempty"`

	// HTTPHeaders are static response headers set on every response served
	// by TLS listeners (they are not applied on plain http listeners).
	HTTPHeaders map[string]string `json:"http_headers,omitempty" yaml:"http_headers,omitempty"`
}

Config is the server configuration passed to Start. It is usually unmarshalled from YAML/JSON; the yaml and json tags give the field names.

func (*Config) ParseListenURLs

func (c *Config) ParseListenURLs() ([]*url.URL, error)

ParseListenURLs parses ListenURLs into URLs, returning an error for any malformed entry.

type GRPCRegistrator

type GRPCRegistrator interface {
	// RegisterGRPC registers the service implementation on the gRPC server.
	RegisterGRPC(*grpc.Server)
}

GRPCRegistrator is an optional interface a Service implements to expose gRPC services; it is invoked once per gRPC server instance (secure and insecure).

type GServer added in v0.14.0

type GServer interface {
	// Name returns server name
	Name() string
	// Configuration of the server
	Configuration() *Config
	// AddService to the server
	AddService(svc Service)
	// Service returns service by name
	Service(name string) Service
	// IsReady returns true when the server is ready to serve
	IsReady() bool
	// StartedAt returns Time when the server has started
	StartedAt() time.Time
	// ListenURLs is the list of URLs that the server listens on
	ListenURLs() []string
	// Hostname is the hostname
	Hostname() string
	// LocalIP is the local IP4
	LocalIP() string
	// Discovery returns Discovery interface
	Discovery() discovery.Discovery
	// Err returns error channel
	Err() <-chan error
	// Close gracefully shuts down all servers/listeners.
	// Client requests will be terminated with request timeout.
	// After timeout, enforce remaning requests be closed immediately.
	Close()
}

GServer is the server handle passed to ServiceFactory functions and returned by Start. Services use it to register themselves and to query server state; it is safe for concurrent reads after Start returns.

func Start

func Start(
	name string,
	cfg *Config,
	container *dig.Container,
	serviceFactories map[string]ServiceFactory,
	opts ...Option,
) (GServer, error)

Start creates the services from serviceFactories, opens the listeners from cfg.ListenURLs and begins serving in background goroutines, returning the running server. The container must provide discovery.Discovery and, when cfg.IdentityMap enables JWT or DPoP, a jwt.Parser. On error any partially opened listeners are closed and the error is returned; on success the caller must eventually call Close. Serve errors are reported on Err.

type KeepAliveCfg

type KeepAliveCfg struct {
	// MinTime is the minimum interval that a client should wait before pinging server.
	MinTime time.Duration `json:"min_time,omitempty" yaml:"min_time,omitempty"`

	// Interval is the frequency of server-to-client ping to check if a connection is alive.
	Interval time.Duration `json:"interval,omitempty" yaml:"interval,omitempty"`

	// Timeout is the additional duration of wait before closing a non-responsive connection, use 0 to disable.
	Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`
}

KeepAliveCfg configures gRPC keepalive. MinTime sets the enforcement policy; Interval and Timeout are only applied when both are positive. MaxConnectionIdle is always 5 minutes.

type Middleware

type Middleware func(handler http.Handler) http.Handler

Middleware wraps an http.Handler; it is applied by WithMiddleware.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option customizes a Server created by Start.

func MaxRecvMsgSize added in v0.33.334

func MaxRecvMsgSize(size int) Option

MaxRecvMsgSize sets the maximum gRPC message size a client can send, overriding Config.MaxRecvMsgSize.

func MaxSendMsgSize added in v0.33.334

func MaxSendMsgSize(size int) Option

MaxSendMsgSize sets the maximum gRPC message size the server can send, overriding Config.MaxSendMsgSize.

func WithMiddleware

func WithMiddleware(otherHandler Middleware) Option

WithMiddleware adds an HTTP middleware to the REST handler chain. It runs after the built-in middlewares (identity, authz, logging), closest to the router; multiple middlewares wrap in the order given.

func WithStreamServerInterceptor

func WithStreamServerInterceptor(other grpc.StreamServerInterceptor) Option

WithStreamServerInterceptor appends a gRPC stream interceptor after the built-in chain (logging, correlation, identity, authz).

func WithUnaryServerInterceptor

func WithUnaryServerInterceptor(other grpc.UnaryServerInterceptor) Option

WithUnaryServerInterceptor appends a gRPC unary interceptor after the built-in chain (panic recovery, validation, correlation, logging, identity, authz).

type RateLimit

type RateLimit struct {
	// Enabled specifies if rate limiting is enabled.
	Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`
	// RequestsPerSecond specifies the maximum number of requests per second.
	RequestsPerSecond int `json:"requests_per_second,omitempty" yaml:"requests_per_second,omitempty"`
	// ExpirationTTL specifies the TTL for token bucket, default 10 mins
	ExpirationTTL time.Duration `json:"expiration_ttl,omitempty" yaml:"expiration_ttl,omitempty"`
	// HeadersIPLookups lists the sources used to identify the client, in order;
	// default is "X-Forwarded-For", "X-Real-IP", "RemoteAddr".
	HeadersIPLookups []string `json:"headers_ip_lookups,omitempty" yaml:"headers_ip_lookups,omitempty"`
	// Metods (sic) restricts limiting to the listed HTTP methods, e.g. "GET", "POST";
	// empty means all methods.
	Metods []string `json:"metods,omitempty" yaml:"metods,omitempty"`
}

RateLimit configures the per-client token bucket rate limiter (github.com/didip/tollbooth) that wraps the HTTP handler.

func (*RateLimit) GetEnabled

func (c *RateLimit) GetEnabled() bool

GetEnabled returns true when rate limiting is configured and enabled; safe on a nil receiver.

type RouteRegistrator

type RouteRegistrator interface {
	// RegisterRoute adds the service HTTP handlers to the router.
	RegisterRoute(restserver.Router)
}

RouteRegistrator is an optional interface a Service implements to expose REST endpoints; it is invoked once per listener when the router is built.

type Server

type Server struct {
	// Listeners are the accepted network listeners, one per unique listen address.
	Listeners []net.Listener
	// contains filtered or unexported fields
}

Server is the GServer implementation returned by Start. It owns the listeners, the per-listener HTTP and gRPC servers, and the registered services. Use Start to construct it; the zero value is not usable.

Example
sigs := make(chan os.Signal, 2)

cfg := &gserver.Config{
	ListenURLs: []string{"https://127.0.0.1:12345", "unix:///tmp/gserver_test.sock"},
	Services:   []string{"test"},
	KeepAlive: gserver.KeepAliveCfg{
		MinTime:  time.Second,
		Interval: time.Second,
		Timeout:  time.Second,
	},
	ServerTLS: &gserver.TLSInfo{
		CertFile:      "testdata/test-server.pem",
		KeyFile:       "testdata/test-server-key.pem",
		TrustedCAFile: "testdata/test-server-rootca.pem",
		ClientCAFile:  "testdata/test-server-rootca.pem", // CA bundle for client certificates
	},
	RateLimit: &gserver.RateLimit{
		RequestsPerSecond: 10,
	},
}

c := mockappcontainer.NewBuilder().
	WithJwtParser(nil).
	WithDiscovery(discovery.New()).
	Container()

fact := map[string]gserver.ServiceFactory{
	"test": testServiceFactory,
}
fmt.Println("starting server")
srv, err := gserver.Start("Empty", cfg, c, fact)
if err != nil {
	panic("unable to start the server: " + err.Error())
}

go func() {
	// Send STOP signal after few seconds,
	// in production the service should listen to
	// os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGUSR2, syscall.SIGABRT events
	time.Sleep(3 * time.Second)
	fmt.Println("sending syscall.SIGTERM signal")
	sigs <- syscall.SIGTERM
}()

// register for signals, and wait to be shutdown
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
// Block until a signal is received.
sig := <-sigs

fmt.Printf("received signal: %v\n", sig)

srv.Close()
fmt.Println("stopped server")
Output:
starting server
sending syscall.SIGTERM signal
received signal: terminated
stopped server

func (*Server) AddService

func (e *Server) AddService(svc Service)

AddService registers svc by its Name, replacing any service with the same name. It must be called from a ServiceFactory, before Start begins serving; the services map is not synchronized.

func (*Server) Close

func (e *Server) Close()

Close gracefully shuts down all servers/listeners. Client requests will be terminated with request timeout. After timeout, enforce remaning requests be closed immediately.

func (*Server) Configuration

func (e *Server) Configuration() *Config

Configuration returns a pointer to the server's copy of the Config; mutating it after Start has no effect on already configured listeners.

func (*Server) Discovery

func (e *Server) Discovery() discovery.Discovery

Discovery returns the discovery.Discovery injected from the container; all services are registered with it under the server name after Start.

func (*Server) Err

func (e *Server) Err() <-chan error

Err returns the channel on which listener/serve errors are reported. The channel is buffered and is never closed; errors are dropped once Close begins.

func (*Server) Hostname

func (e *Server) Hostname() string

Hostname is the hostname

func (*Server) IsReady

func (e *Server) IsReady() bool

IsReady returns true when every registered service reports IsReady.

func (*Server) ListenURLs

func (e *Server) ListenURLs() []string

ListenURLs returns the configured Config.ListenURLs (not the resolved listener addresses).

func (*Server) LocalIP

func (e *Server) LocalIP() string

LocalIP returns the local IPv4 address detected at startup, or 127.0.0.1 when it could not be determined.

func (*Server) Name

func (e *Server) Name() string

Name returns server name

func (*Server) Service

func (e *Server) Service(name string) Service

Service returns the registered service with the given name, or nil.

func (*Server) StartedAt

func (e *Server) StartedAt() time.Time

StartedAt returns Time when the server has started

type Service

type Service interface {
	// Name returns the unique service name used as the key in GServer.Service.
	Name() string
	// Close releases the service resources; it is called by Server.Close before
	// the listeners are shut down.
	Close()
	// IsReady indicates that service is ready to serve its end-points
	IsReady() bool
}

Service is a named sub-service hosted by a Server. Services are created by a ServiceFactory and registered with GServer.AddService; a Service may additionally implement RouteRegistrator, GRPCRegistrator or StartSubcriber.

type ServiceFactory

type ServiceFactory func(GServer) any

ServiceFactory builds a Service for the given server. The returned value is passed to dig.Container.Invoke, so it must be a function whose parameters are resolved from the container; the function itself should call GServer.AddService.

type StartSubcriber

type StartSubcriber interface {
	// OnStarted is called when the server started and
	// is ready to serve requests
	OnStarted() error
}

StartSubcriber is an optional interface a Service can implement to be notified once the server has started.

type SwaggerCfg

type SwaggerCfg struct {
	// Enabled allows Swagger
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Files is a map of service name to location
	Files map[string]string `json:"files" yaml:"files"`
}

SwaggerCfg specifies the configuration for Swagger. It is not used by gserver itself and is provided for services that serve Swagger files.

type TLSInfo

type TLSInfo struct {
	// CertFile specifies location of the cert
	CertFile string `json:"cert,omitempty" yaml:"cert,omitempty"`

	// KeyFile specifies location of the key
	KeyFile string `json:"key,omitempty" yaml:"key,omitempty"`

	// TrustedCAFile specifies location of the trusted root CA bundle
	TrustedCAFile string `json:"trusted_ca,omitempty" yaml:"trusted_ca,omitempty"`

	// ClientCAFile specifies location of the CA bundle used to verify client certificates
	ClientCAFile string `json:"client_ca,omitempty" yaml:"client_ca,omitempty"`

	// CRLFile specifies location of the CRL
	CRLFile string `json:"crl,omitempty" yaml:"crl,omitempty"`

	// OCSPFile specifies location of the OCSP response
	OCSPFile string `json:"ocsp,omitempty" yaml:"ocsp,omitempty"`

	// CipherSuites optionally restricts the TLS cipher suites (by name)
	CipherSuites []string `json:"cipher_suites,omitempty" yaml:"cipher_suites,omitempty"`

	// ClientCertAuth, when true, requires and verifies a client certificate;
	// otherwise a client certificate is verified only if presented.
	ClientCertAuth *bool `json:"client_cert_auth,omitempty" yaml:"client_cert_auth,omitempty"`
}

TLSInfo is the server TLS configuration. Cert and key files are watched and reloaded by pkg/transport; CRLFile and OCSPFile are currently not used.

func (*TLSInfo) Empty

func (info *TLSInfo) Empty() bool

Empty returns true if the receiver is nil or either CertFile or KeyFile is unset.

func (*TLSInfo) GetClientCertAuth

func (info *TLSInfo) GetClientCertAuth() bool

GetClientCertAuth returns true when ClientCertAuth is set and true.

func (*TLSInfo) String

func (info *TLSInfo) String() string

String returns a loggable summary of the TLS file locations; safe on a nil receiver.

type Validator added in v0.35.366

type Validator interface {
	// Validate returns an error (typically a gRPC status) when the request is invalid.
	Validate(ctx context.Context) error
}

Validator is implemented by request messages that can validate themselves; NewRequestValidationUnaryInterceptor calls it before the handler.

Directories

Path Synopsis
Package credentials implements gRPC transport and per-RPC credentials for porto clients and servers.
Package credentials implements gRPC transport and per-RPC credentials for porto clients and servers.
Package roles maps authenticated callers to porto roles for both HTTP and gRPC requests.
Package roles maps authenticated callers to porto roles for both HTTP and gRPC requests.

Jump to

Keyboard shortcuts

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