grpcserver

package
v1.0.14 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 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 grpcserver demonstrates how to build a self-contained gRPC server on top of component-base's generic gRPC server (pkg/generic_server/server) and the five-layer gRPC framework (pkg/generic_server/framework/grpc). The structure mirrors the bifrost project's server.

Five-layer architecture (based on go-kit):

Transport layer  transport.go / handler.go / decoder.go / encoder.go  -- pb service impls, handlers, codecs
Endpoint layer   endpoint.go                                          -- Endpoint[DomainReq, DomainResp]
Middleware layer middleware.go                                        -- Middlewares[ServiceFactory]
Service layer    service.go                                           -- ServiceFactory / DemoService
Store layer      store.go                                             -- StoreFactory / DemoStore (in-memory)

Assembly and lifecycle:

Options -> CreateConfigFromOptions -> GRPCServerConfig
        -> NewServer(ctx, cfg): cfg.Complete().NewGRPCServer(ctx, hooks)
        -> GenericGRPCServer -> PrepareRun() -> Run()

bizHooks implements GRPCServerBizHooks[Factory, DemoEndpoints, ServiceFactory, StoreFactory]; each method only delegates to its own layer constructor. The call order is InitStore -> InitService -> RegisteredMiddlewares -> InitEndpoints -> InitTransport -> ServiceRegistrations -> Startup -> Shutdown, with all five layers initialized under the generic server's control. ServiceRegistrations receives the initialized transport layer and delegates to register.go's NewServiceRegistrations, which declares service name + implementation + pb register func. The registration control flow (health status transitions, mounting implementations) is owned by the framework's svcregisterv1.GenerateServiceRegisters; the generic server then registers the services to grpc.Server (and to the RA, if configured).

The Demo service covers two RPC shapes:

  • Echo: unary RPC, demonstrating the decode -> endpoint -> encode pipeline.
  • Download: server-streaming RPC; transport.StreamHandler encapsulates "compute + chunked send", so the pb-service method only calls ServeGRPCStream.

ChunkSize is injected by the generic server via the InitTransport hook, sourced from server.GRPCServing.ChunkSize. component-base removed the standalone transport Options; chunkSize is injected into the StreamHandler at construction (NewDemoHandlers), which calls StreamSendMsg via ServeStream.

Reusing this example in a business project

  1. Copy this directory and rename the package; replace the .proto files under api/protobuf-spec with your business protocol and regenerate the pb code via cmd/genpb's go:generate.
  2. Replace the business implementations layer by layer (keep each layer's Factory/interface contracts and file layout): store.go replace the in-memory impl with real storage (MySQL/Redis, etc.); service.go replace with business service logic; middleware.go add/remove named middlewares as needed (keys match Options.Middlewares); endpoint.go / handler.go / decoder.go / encoder.go / transport.go one endpoint/handler/codec/pb-service set per pb service; register.go declare NewServiceRegistration per service (name + impl + pb register func).
  3. Keep unchanged: the hooks.go delegation pattern (each Init only calls its own layer constructor, no cross-layer assembly) and server.go's Options -> Config -> NewServer assembly chain. The registration control flow (health status transitions, mounting order) is owned by the framework's svcregisterv1.GenerateServiceRegisters; business code must never set health status by hand.
  4. Naming conventions: each layer entry point is XxxFactory; registration names follow "<RA prefix>.<proto package>.<Service>" and double as the gRPC health-check keys; streaming RPCs always send chunks via transport.StreamHandler.

Running the server

func main() {
    if err := grpcserver.Run(grpcserver.NewOptions()); err != nil {
        log.Fatal(err)
    }
}

It listens on 127.0.0.1:8081 (insecure) by default. See grpcserver_test.go for pb client call examples.

Testing

go test ./examples/grpcserver/...

The pb code is generated by the go:generate command in cmd/genpb/gen_grpcserver_protobuf.go (mirroring bifrost).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateConfigFromOptions

CreateConfigFromOptions validates, completes and applies options to a server config.

func GetMiddlewares

func GetMiddlewares() grpcmwv1.Middlewares[ServiceFactory]

GetMiddlewares returns the named middleware registry for the service factory. The generic server installs the middlewares listed in GRPCServerConfig.Middlewares by looking them up here, wrapping the service factory in order.

func NewBizHooks

func NewBizHooks() *bizHooks

NewBizHooks creates the business hooks. The hooks are stateless: chunkSize is injected by the generic server via InitTransport, and ServiceRegistrations receives the initialized transport factory.

func NewServer

NewServer builds a generic gRPC server from the config and business hooks.

func NewServiceRegistrations

func NewServiceRegistrations(txp Factory) []svcregisterv1.ServiceRegistration

NewServiceRegistrations is the default registration scheme. It carries only business decisions (service name, implementation, pb register func); the registration control flow (health status transitions, invocation order) is owned by the framework service_register package.

func Run

func Run(opts *Options) error

Run wires options -> config -> server and runs until shutdown.

Types

type DemoEndpoints

type DemoEndpoints interface {
	Echo() epv1.Endpoint[string, string]
	Download() epv1.Endpoint[string, []byte]
}

DemoEndpoints wraps the service methods into generic go-kit endpoints. It is the endpoint layer, mirroring bifrost's endpoint/v1.

func NewDemoEndpoints

func NewDemoEndpoints(svc DemoService) DemoEndpoints

NewDemoEndpoints creates the endpoint set for the demo service.

type DemoHandlers

type DemoHandlers interface {
	Echo() transportv1.Handler[*pbv1.EchoRequest, *pbv1.EchoResponse]
	Download() transportv1.StreamHandler[*pbv1.DownloadRequest, *pbv1.Chunk]
}

DemoHandlers is the transport-layer handler set for the demo service. Each handler is a lazily-initialized singleton, mirroring bifrost's handler factory.

func NewDemoHandlers

func NewDemoHandlers(eps DemoEndpoints, chunkSize int) DemoHandlers

NewDemoHandlers creates the handler set from the endpoint layer. chunkSize is injected from the generic server config for the streaming handler.

type DemoService

type DemoService interface {
	Echo(ctx context.Context, message string) (string, error)
	Download(ctx context.Context, key string) ([]byte, error)
}

DemoService defines the business operations for the demo resource.

func NewDemoService

func NewDemoService(store DemoStore) DemoService

NewDemoService creates a DemoService backed by the given store.

type DemoStore

type DemoStore interface {
	Get(key string) ([]byte, error)
	Put(key string, data []byte) error
}

DemoStore defines the storage operations for the demo resource.

type Factory

type Factory interface {
	Demo() pbv1.DemoServer
}

Factory is the transport-layer factory producing pb service implementations that can be registered onto a grpc.Server. It mirrors bifrost's transport/v1.Factory. Adaptation point: add one method per pb service when the project grows.

func NewFactory

func NewFactory(handlers DemoHandlers) Factory

NewFactory creates the transport factory. The streaming chunkSize is already injected into the StreamHandler at construction (component-base removed the standalone transport Options struct).

type Options

Options holds the configuration options for the example gRPC server.

func NewOptions

func NewOptions() *Options

NewOptions creates Options with sensible defaults for the example.

type ServiceFactory

type ServiceFactory interface {
	Demo() DemoService
}

ServiceFactory provides access to all service instances. It is the entry point of the service layer, mirroring bifrost's service/v1.ServiceFactory.

func NewServiceFactory

func NewServiceFactory(store StoreFactory) ServiceFactory

NewServiceFactory creates a ServiceFactory backed by the given store.

type StoreFactory

type StoreFactory interface {
	Demo() DemoStore
}

StoreFactory provides access to all store instances. It is the entry point of the store layer, mirroring bifrost's store/v1.StoreFactory.

func NewStoreFactory

func NewStoreFactory() StoreFactory

NewStoreFactory creates an in-memory StoreFactory for demonstration.

Directories

Path Synopsis
api
cmd
genpb command

Jump to

Keyboard shortcuts

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