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 ¶
- 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.
- 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).
- 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.
- 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 ¶
- func CreateConfigFromOptions(opts *Options) (...)
- func GetMiddlewares() grpcmwv1.Middlewares[ServiceFactory]
- func NewBizHooks() *bizHooks
- func NewServer(ctx context.Context, ...) ...
- func NewServiceRegistrations(txp Factory) []svcregisterv1.ServiceRegistration
- func Run(opts *Options) error
- type DemoEndpoints
- type DemoHandlers
- type DemoService
- type DemoStore
- type Factory
- type Options
- type ServiceFactory
- type StoreFactory
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CreateConfigFromOptions ¶
func CreateConfigFromOptions(opts *Options) (*genericserver.GRPCServerConfig[Factory, DemoEndpoints, ServiceFactory, StoreFactory], error)
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 ¶
func NewServer(ctx context.Context, cfg *genericserver.GRPCServerConfig[Factory, DemoEndpoints, ServiceFactory, StoreFactory]) *genericserver.GenericGRPCServer[Factory, DemoEndpoints, ServiceFactory, StoreFactory]
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.
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 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 ¶
type Options struct {
GRPCServerRunOptions *genericoptions.GRPCServerRunOptions[Factory, DemoEndpoints, ServiceFactory, StoreFactory]
GRPCServingOptions *genericoptions.GRPCServingOptions[Factory, DemoEndpoints, ServiceFactory, StoreFactory]
InsecureServingOptions *genericoptions.InsecureServingOptions[ServiceFactory, StoreFactory]
}
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.