package app import ( "errors" "net" "sync" "google.golang.org/grpc" healthgrpc "google.golang.org/grpc/health/grpc_health_v1" activityv1 "hyapp/api/proto/activity/v1" "hyapp/pkg/grpchealth" "hyapp/services/activity-service/internal/config" activityservice "hyapp/services/activity-service/internal/service/activity" "hyapp/services/activity-service/internal/storage/memory" grpcserver "hyapp/services/activity-service/internal/transport/grpc" ) // App 装配 activity-service gRPC 入口和底座依赖。 type App struct { server *grpc.Server listener net.Listener health *grpchealth.ServingChecker closeOnce sync.Once } // New 初始化 activity-service 应用。 func New(cfg config.Config) (*App, error) { listener, err := net.Listen("tcp", cfg.GRPCAddr) if err != nil { return nil, err } server := grpc.NewServer() repository := memory.NewRepository() svc := activityservice.New(activityservice.Config{NodeID: cfg.NodeID}, repository) activityv1.RegisterActivityServiceServer(server, grpcserver.NewServer(svc)) health := grpchealth.NewServingChecker("activity-service") healthgrpc.RegisterHealthServer(server, grpchealth.NewServer(health)) return &App{ server: server, listener: listener, health: health, }, nil } // Run 启动 gRPC 服务。 func (a *App) Run() error { a.health.MarkServing() err := a.server.Serve(a.listener) a.health.MarkStopped() if errors.Is(err, grpc.ErrServerStopped) { return nil } return err } // Close 关闭 gRPC 服务。 func (a *App) Close() { a.closeOnce.Do(func() { a.health.MarkDraining() a.server.GracefulStop() }) }