Documentation
¶
Overview ¶
Package serverx provides Kernel's opinionated service assembly layer.
It is intentionally above low-level transport/http and transport/grpc. Business components should ask serverx for managed servers and clients instead of wiring raw transports, middleware, system routes, governance validation, and lifecycle hooks by hand.
Index ¶
- func ClientMiddlewareForDownstream(policy clientpolicyx.DownstreamPolicy, provider ratelimitx.Provider) ([]middleware.Middleware, error)
- func RegisterGatewayRoutes(ctx context.Context, registry gatewayx.RouteRegistry, ...) error
- func RegisterServiceGatewayRoutes(ctx context.Context, registry gatewayx.RouteRegistry, modules ...ServiceModule) error
- func RegisterServiceGatewayRoutesWithFilter(ctx context.Context, registry gatewayx.RouteRegistry, ...) error
- func ServerMiddlewareFromProviders(_ context.Context, p RuntimeProviders) []middleware.Middleware
- type App
- func BuildService(ctx context.Context, cfg Config, module ServiceModule, svc any, ...) (*App, error)
- func BuildServiceFromFactory(ctx context.Context, cfg Config, module ServiceModule, factory ServiceFactory, ...) (*App, error)
- func New(ctx context.Context, cfg Config, opts ...Option) (*App, error)
- func NewWithDefaultGovernance(ctx context.Context, cfg Config, opts ...Option) (*App, error)
- type AuditConfig
- type BuildOption
- type Config
- type DatabaseConfig
- type FileConfig
- type GRPCConfig
- type HTTPConfig
- type Option
- type ProviderFactory
- type ProviderRefConfig
- type RuntimeProviders
- type SecurityConfig
- type ServiceDeps
- type ServiceFactory
- type ServiceModule
- type SystemRoutesConfig
- type SystemRoutesFileConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClientMiddlewareForDownstream ¶
func ClientMiddlewareForDownstream(policy clientpolicyx.DownstreamPolicy, provider ratelimitx.Provider) ([]middleware.Middleware, error)
ClientMiddlewareForDownstream builds the standard client governance chain for one downstream.
func RegisterGatewayRoutes ¶
func RegisterGatewayRoutes(ctx context.Context, registry gatewayx.RouteRegistry, manifests ...gatewayx.Manifest) error
RegisterGatewayRoutes publishes generated route manifests through the Kernel route registry abstraction. In local validation this is normally a gatewayx.MemoryRegistry; production should provide an etcd-backed registry.
func RegisterServiceGatewayRoutes ¶
func RegisterServiceGatewayRoutes(ctx context.Context, registry gatewayx.RouteRegistry, modules ...ServiceModule) error
RegisterServiceGatewayRoutes registers generated module manifests into the route registry without filtering. Prefer RegisterServiceGatewayRoutesWithFilter for public/internal/ops gateway profiles so internal routes do not leak into the wrong registry.
func RegisterServiceGatewayRoutesWithFilter ¶ added in v0.2.2
func RegisterServiceGatewayRoutesWithFilter(ctx context.Context, registry gatewayx.RouteRegistry, filter gatewayx.RouteFilter, modules ...ServiceModule) error
RegisterServiceGatewayRoutesWithFilter registers generated module manifests after applying a profile-aware route filter. This is the recommended path for production gateways: public gateways should use gatewayx.PublicRouteFilter(), internal gateways should use gatewayx.InternalRouteFilter(), and ops gateways should use an explicit allowlist.
func ServerMiddlewareFromProviders ¶
func ServerMiddlewareFromProviders(_ context.Context, p RuntimeProviders) []middleware.Middleware
ServerMiddlewareFromProviders is a functional helper for tests and custom bootstrap code that do not need a full serverx.App yet.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the assembled service entrypoint.
func BuildService ¶
func BuildService(ctx context.Context, cfg Config, module ServiceModule, svc any, opts ...BuildOption) (*App, error)
BuildService assembles a generated service module with a concrete service implementation and Kernel-managed transports/middleware.
func BuildServiceFromFactory ¶
func BuildServiceFromFactory(ctx context.Context, cfg Config, module ServiceModule, factory ServiceFactory, opts ...BuildOption) (*App, error)
BuildServiceFromFactory assembles a generated service module after loading Kernel-managed dependencies. Provider SDKs and database construction stay in boot/provider layers; generated service handlers receive only ServiceDeps.
func New ¶
New validates governance, creates managed transports, installs system routes, and returns a Kernel app. It does not start serving until Run is called.
func NewWithDefaultGovernance ¶
NewWithDefaultGovernance is a convenience constructor for demos and early services. Production services should pass explicit autowire options once providers are configured.
func (*App) GRPC ¶
func (a *App) GRPC() *transportgrpc.Server
func (*App) HTTP ¶
func (a *App) HTTP() *transporthttp.Server
type AuditConfig ¶
type BuildOption ¶
type BuildOption func(*buildOptions)
func WithAccessProviders ¶
func WithAccessProviders(p accessx.Providers) BuildOption
func WithAllowAnonymous ¶
func WithAllowAnonymous(allow bool) BuildOption
func WithCredentialExtractor ¶
func WithCredentialExtractor(e authnmw.CredentialExtractor) BuildOption
func WithProviderFactory ¶
func WithProviderFactory(f ProviderFactory) BuildOption
type Config ¶
type Config struct {
Name string
Version string
Deployment bootx.Deployment
HTTP HTTPConfig
GRPC GRPCConfig
SystemRoutes SystemRoutesConfig
Governance bootx.GovernanceConfig
// Downstreams are caller-side governance contracts. They are validated at
// startup and should later be used by Kernel client factories.
Downstreams []clientpolicyx.DownstreamPolicy
Security SecurityConfig
Database DatabaseConfig
}
Config is the high-level Kernel service contract consumed by serverx.
func DecodeFileConfig ¶
func DecodeFileConfig(fc FileConfig) (Config, error)
DecodeFileConfig converts the human-facing FileConfig into the runtime Config. It is split out for tests and for services that assemble config from multiple sources before booting.
func LoadConfig ¶
LoadConfig loads serverx.Config from an already initialized configx.Config.
func LoadConfigFile ¶
LoadConfigFile loads a Kernel service config from YAML/JSON/TOML sources supported by configx/file. New services should use this during boot, then pass the returned Config to serverx.New.
type DatabaseConfig ¶
type DatabaseConfig struct {
Enabled bool
DBX dbx.Config
Migration migrationx.Config
}
DatabaseConfig declares Kernel-managed database boot. It deliberately keeps schema SQL outside proto: migrations/ remains the source of truth, dbx opens the GORM-backed pool, and migrationx applies or validates SQL migrations.
type FileConfig ¶
type FileConfig struct {
App struct {
Name string `json:"name" yaml:"name"`
Version string `json:"version" yaml:"version"`
} `json:"app" yaml:"app"`
Deployment struct {
Replicas int `json:"replicas" yaml:"replicas"`
} `json:"deployment" yaml:"deployment"`
Server struct {
HTTP struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Address string `json:"address" yaml:"address"`
Timeout string `json:"timeout" yaml:"timeout"`
} `json:"http" yaml:"http"`
GRPC struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Address string `json:"address" yaml:"address"`
Timeout string `json:"timeout" yaml:"timeout"`
} `json:"grpc" yaml:"grpc"`
} `json:"server" yaml:"server"`
SystemRoutes SystemRoutesFileConfig `json:"system_routes" yaml:"system_routes"`
Database struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Driver string `json:"driver" yaml:"driver"`
DSN string `json:"dsn" yaml:"dsn"`
AutoCreateDatabase bool `json:"auto_create_database" yaml:"auto_create_database"`
MaxOpenConns int `json:"max_open_conns" yaml:"max_open_conns"`
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns"`
QueryTimeout string `json:"query_timeout" yaml:"query_timeout"`
SlowQueryThreshold string `json:"slow_query_threshold" yaml:"slow_query_threshold"`
Debug bool `json:"debug" yaml:"debug"`
DryRun bool `json:"dry_run" yaml:"dry_run"`
Migration migrationx.Config `json:"migration" yaml:"migration"`
} `json:"database" yaml:"database"`
Security struct {
Authn struct {
Provider string `json:"provider" yaml:"provider"`
Required bool `json:"required" yaml:"required"`
} `json:"authn" yaml:"authn"`
Authz struct {
Provider string `json:"provider" yaml:"provider"`
Required bool `json:"required" yaml:"required"`
} `json:"authz" yaml:"authz"`
Audit struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Provider string `json:"provider" yaml:"provider"`
} `json:"audit" yaml:"audit"`
} `json:"security" yaml:"security"`
}
FileConfig is the YAML/JSON friendly service configuration contract used by Kernel-generated services. It intentionally mirrors Config, but keeps duration fields as strings so humans can write values like "2s" in config files.
type Option ¶
type Option func(*options)
func WithGRPCOptions ¶
func WithGRPCOptions(opts ...transportgrpc.ServerOption) Option
func WithHTTPOptions ¶
func WithHTTPOptions(opts ...transporthttp.ServerOption) Option
func WithKernelOptions ¶
func WithRuntimeProviders ¶
func WithRuntimeProviders(p RuntimeProviders) Option
WithRuntimeProviders installs provider-neutral authn/authz/audit/admission middleware into serverx.New. It exists so a service created by `kernel new` can be wired by providers instead of raw middleware.
func WithServerMiddleware ¶
func WithServerMiddleware(m ...middleware.Middleware) Option
WithServerMiddleware adds already-built Kernel middleware to both HTTP and gRPC servers.
type ProviderFactory ¶
type ProviderFactory interface {
BuildAccessProviders(ctx context.Context, cfg Config) (accessx.Providers, error)
}
ProviderFactory creates provider-neutral Kernel providers from Config. Concrete factories may live in contrib/authn/casdoor, contrib/authz/spicedb, or platform boot packages. Business services should not instantiate provider SDKs directly.
type ProviderRefConfig ¶
type RuntimeProviders ¶
type RuntimeProviders struct {
Access accessx.Providers
// AccessResolver is normally generated from proto access policy. It maps a
// request operation to an accessx.Check consumed by accessx.Guard.
AccessResolver accessmw.Resolver
// RequestInfoResolver is normally generated from proto metadata. It fills
// requestx.Info before authn/authz/audit/metrics run.
RequestInfoResolver requestx.Resolver
// Admission contains Kubernetes-apiserver-style mutating/validating hooks.
Admission admissionx.Chain
// CredentialExtractor allows gateways and services to choose bearer,
// internal delegation token, API key, or other extraction strategies.
CredentialExtractor authnmw.CredentialExtractor
AllowAnonymous bool
}
RuntimeProviders is the provider-neutral server wiring contract used by Kernel services. Concrete engines such as Casdoor and SpiceDB must be adapted into accessx.Providers before they enter serverx. Business services should not import provider SDKs directly.
func (RuntimeProviders) ServerMiddleware ¶
func (p RuntimeProviders) ServerMiddleware() []middleware.Middleware
ServerMiddleware builds the opinionated Kernel middleware chain from runtime providers. This is the preferred path for generated services.
type SecurityConfig ¶
type SecurityConfig struct {
Authn ProviderRefConfig
Authz ProviderRefConfig
Audit AuditConfig
}
SecurityConfig declares provider names used by service boot factories. It is configuration only; concrete Casdoor/SpiceDB construction lives behind ProviderFactory implementations, not business handlers.
type ServiceDeps ¶
ServiceDeps are Kernel-managed dependencies produced during service boot. Generated services should accept these through a ServiceFactory so data repos, provider sets, and managed DB are injected after config/migration/provider loading, instead of being hand-wired in main.go.
type ServiceFactory ¶
type ServiceFactory func(ctx context.Context, deps ServiceDeps) (any, error)
ServiceFactory creates the concrete generated service implementation from Kernel-managed dependencies. This is the preferred autoload path.
type ServiceModule ¶
type ServiceModule struct {
Name string
// GatewayManifest is generated from google.api.http + aisphere.access.v1.policy.
GatewayManifest gatewayx.Manifest
// RequestInfoResolver and AccessResolver are generated from proto service/RPC
// metadata and access policy. Runtime code must not re-derive this from raw
// path/method strings.
RequestInfoResolver requestx.Resolver
AccessResolver accessmw.Resolver
// RegisterGRPC registers the generated gRPC server against Kernel's managed
// gRPC transport. The service implementation is passed as any because
// generated code owns the concrete interface assertion.
RegisterGRPC func(*transportgrpc.Server, any) error
// RegisterHTTP registers generated HTTP/JSON routes against Kernel's managed
// HTTP transport. Optional for services that only expose gRPC internally.
RegisterHTTP func(*transporthttp.Server, any) error
// RegisterGatewayInvokers registers generated Gateway -> gRPC operation
// invokers. Gateways use this when linking compiled service clients.
RegisterGatewayInvokers func(*gatewayx.InvokerRegistry, any) error
// RegisterData is optional. Generated or hand-written data modules can use it
// to construct repositories from Kernel-managed dbx.DB. Migrations remain SQL
// files under migrations/; this hook is only for safe repo construction.
RegisterData func(dbx.DB) (any, error)
}
ServiceModule is the generated service contract consumed by serverx.
protoc-gen-go-kernel / protoc-gen-go-gateway should generate one module per proto service. The module carries generated metadata and registration hooks so service boot code does not manually wire authn/authz/audit, Gateway manifests, HTTP routes, or gRPC servers.
func (ServiceModule) ModuleName ¶
func (m ServiceModule) ModuleName() string
func (ServiceModule) Validate ¶
func (m ServiceModule) Validate() error
type SystemRoutesConfig ¶
SystemRoutesConfig controls generic server routes owned by Kernel, not by business proto.