2026-06-23 11:53:00 +08:00

57 lines
2.0 KiB
Go

// Package health wires standard gRPC health and the optional HTTP readiness endpoint.
package health
import (
"errors"
"google.golang.org/grpc"
healthgrpc "google.golang.org/grpc/health/grpc_health_v1"
"hyapp/pkg/grpchealth"
"hyapp/pkg/healthhttp"
)
// Config describes one service's shared gRPC health and HTTP readiness endpoint.
type Config struct {
ServiceName string
HTTPAddr string
NodeID string
Dependencies []grpchealth.Dependency
}
// New registers standard gRPC health and creates the companion HTTP health server.
// Both endpoints share one checker so readiness/draining cannot diverge between CLB and gRPC probes.
func New(server *grpc.Server, cfg Config) (*grpchealth.ServingChecker, *healthhttp.Server, error) {
if server == nil {
return nil, nil, errors.New("grpc server is required")
}
health := grpchealth.NewServingChecker(cfg.ServiceName, cfg.Dependencies...)
healthHTTP, err := Register(server, health, cfg.HTTPAddr, cfg.NodeID)
if err != nil {
return nil, nil, err
}
return health, healthHTTP, nil
}
// Register exposes an existing checker through standard gRPC health and HTTP readiness.
// Services with richer runtime checks keep their domain-specific checker but share the same transport wiring.
func Register(server *grpc.Server, checker grpchealth.Checker, httpAddr string, nodeID string) (*healthhttp.Server, error) {
if server == nil {
return nil, errors.New("grpc server is required")
}
if checker == nil {
return nil, errors.New("health checker is required")
}
healthgrpc.RegisterHealthServer(server, grpchealth.NewServer(checker))
return healthhttp.New(httpAddr, nodeID, checker)
}
// NewHTTP creates the shared checker and HTTP readiness endpoint for services that do not expose gRPC.
func NewHTTP(cfg Config) (*grpchealth.ServingChecker, *healthhttp.Server, error) {
health := grpchealth.NewServingChecker(cfg.ServiceName, cfg.Dependencies...)
healthHTTP, err := healthhttp.New(cfg.HTTPAddr, cfg.NodeID, health)
if err != nil {
return nil, nil, err
}
return health, healthHTTP, nil
}