server

package
v0.1.0-alpha.20260716 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Module = fx.Options(
	fx.Provide(func(f *metrics.Factory) *Reporter {
		return NewReporter(f.ForSubsystem("server"))
	}),
	fx.Invoke(func(p ServerParams) error {
		if err := p.Config.Validate(); err != nil {
			return fmt.Errorf("invalid configuration: %w", err)
		}

		opts := make([]Option, 0, 6)
		opts = append(
			opts,
			WithCredentials(p.creds()),
			WithServerCodec(p.Codec),
			WithStreamInterceptor(p.Reporter.StreamInterceptor()),
			WithUnknownServiceHandler(p.Handler),
		)

		if p.Logger != nil {
			opts = append(opts, WithLogger(p.Logger))
		}

		if p.HealthCheck != nil {
			opts = append(opts, WithHealthCheck(p.HealthCheck))
		}

		svr, err := New(opts...)
		if err != nil {
			return fmt.Errorf("failed to create server: %w", err)
		}

		p.Lifecycle.Append(fx.Hook{
			OnStart: func(context.Context) error {
				lis, err := (&net.ListenConfig{}).Listen(
					p.Context,
					"tcp",
					p.Config.Listen.HostPort,
				)
				if err != nil {
					return fmt.Errorf("failed to create listener: %w", err)
				}

				go func() {
					defer func() { _ = lis.Close() }()

					if err := svr.Start(p.Context, lis); err != nil {

						_ = p.Shutdowner.Shutdown(fx.ExitCode(1))
					}
				}()

				return nil
			},
			OnStop: svr.Stop,
		})

		return nil
	}),
)

Module is the fx module that constructs a Server from ServerParams and binds its lifecycle to the application.

Functions

This section is empty.

Types

type Credentials

type Credentials interface {
	ServerOption() (grpc.ServerOption, error)
	Encrypted() bool
}

Credentials produces the grpc.ServerOption used to configure transport security for inbound connections and reports whether that transport is encrypted.

type HealthCheck

type HealthCheck interface {
	Interval() time.Duration
	Status(context.Context) grpc_health_v1.HealthCheckResponse_ServingStatus
}

HealthCheck reports the server's serving status on a fixed cadence. Interval controls how often Status is invoked to refresh the status exposed via the gRPC health service.

func HealthCheckFunc

HealthCheckFunc adapts a function into a HealthCheck that polls at the given interval.

type Option

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

Option configures a Server at construction time.

func WithCredentials

func WithCredentials(creds Credentials) Option

WithCredentials sets the transport credentials used for inbound connections.

func WithHealthCheck

func WithHealthCheck(hc HealthCheck) Option

WithHealthCheck sets the HealthCheck used to drive the gRPC health service's serving status.

func WithLogger

func WithLogger(log logger.Logger) Option

WithLogger sets the logger used by the server.

func WithServerCodec

func WithServerCodec(c encoding.CodecV2) Option

WithServerCodec forces the codec used for all messages on this server. A pass-through codec paired with WithUnknownServiceHandler enables transparent proxying while locally registered services keep working via codec delegation.

func WithService

func WithService(fn func(grpc.ServiceRegistrar)) Option

WithService registers gRPC services on the server. The callback receives the underlying server as a grpc.ServiceRegistrar, so callers register via the generated pb.RegisterXxxServer(reg, impl) functions.

func WithStreamInterceptor

func WithStreamInterceptor(in ...grpc.StreamServerInterceptor) Option

WithStreamInterceptor appends stream server interceptors. They are chained in the order supplied across all calls and run before the handler.

func WithUnaryInterceptor

func WithUnaryInterceptor(in ...grpc.UnaryServerInterceptor) Option

WithUnaryInterceptor appends unary server interceptors. They are chained in the order supplied across all calls and run before the handler.

func WithUnknownServiceHandler

func WithUnknownServiceHandler(h grpc.StreamHandler) Option

WithUnknownServiceHandler installs a catch-all handler invoked for any method that is not a locally registered service. Used to transparently forward unmatched requests.

type Reporter

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

Reporter records server-layer telemetry to Prometheus: per-RPC latency and completed-request counts by gRPC status code, both labeled by method. The method label set is not known at startup, so handles are resolved per call via WithLabelValues rather than pre-resolved. A Reporter is safe for concurrent use.

Cardinality assumption: method comes from the request line, and the proxy serves every request through a catch-all handler, so any distinct method string a client sends becomes a new series. This is bounded only for trusted callers (real Temporal SDK clients use a fixed method set); a client sending arbitrary method paths can grow the series set without bound. The proxy therefore assumes trusted callers and must not be exposed directly to untrusted clients without first bounding this label. namespace is never a label for the same reason.

func NewReporter

func NewReporter(f *metrics.Factory) *Reporter

NewReporter builds the Prometheus-backed Reporter. f must already be scoped to the "server" subsystem by the caller.

func (*Reporter) Observe

func (r *Reporter) Observe(method string, code codes.Code, d time.Duration)

Observe records one completed RPC: its duration on the method histogram and a count on the (method, code) counter.

func (*Reporter) StreamInterceptor

func (r *Reporter) StreamInterceptor() grpc.StreamServerInterceptor

StreamInterceptor returns a stream server interceptor that times the handler and records the RPC's duration and final gRPC status code. It covers all forwarded traffic, which grpc-go serves through the unknown-service handler as streams. The local health service's unary Check is not metered, since unary calls do not pass through a stream interceptor; its streaming Watch, if a client uses it, would be metered under its own method name.

type Server

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

Server is a gRPC server with a built-in health service and a configurable periodic health check.

func New

func New(sopts ...Option) (*Server, error)

New constructs a Server. When no options are supplied, it uses insecure credentials, a default health check that always reports SERVING, and a CLI logger.

func (*Server) Start

func (s *Server) Start(ctx context.Context, lis net.Listener) error

Start serves on lis and blocks until the server stops. It also kicks off the periodic health check, which runs until ctx is cancelled or Server.Stop is called.

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop gracefully shuts the server down, halting the health check loop and waiting for in-flight RPCs to complete.

type ServerParams

type ServerParams struct {
	fx.In
	Lifecycle  fx.Lifecycle
	Shutdowner fx.Shutdowner

	// Required values
	Context  context.Context
	Config   *config.Config
	Codec    encoding.CodecV2
	Handler  grpc.StreamHandler
	Reporter *Reporter

	// Optional values
	HealthCheck HealthCheck   `optional:"true"`
	Logger      logger.Logger `optional:"true"`
}

ServerParams collects the fx-provided dependencies needed to construct and run a Server. Context, Config, Codec, Handler, and Reporter are required; the Codec and Handler are the transparent-forwarding pieces supplied by the router module, and the Reporter is provided by this module's own fx.Provide. HealthCheck and Logger are optional and fall back to the defaults used by New when not supplied.

Jump to

Keyboard shortcuts

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