serverx

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2026 License: MIT Imports: 25 Imported by: 0

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

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 PublishServiceGatewayRoutes added in v0.2.4

func PublishServiceGatewayRoutes(ctx context.Context, publisher gatewayx.ManifestPublisher, modules ...ServiceModule) error

PublishServiceGatewayRoutes publishes generated service module manifests without filtering.

func PublishServiceGatewayRoutesWithFilter added in v0.2.4

func PublishServiceGatewayRoutesWithFilter(ctx context.Context, publisher gatewayx.ManifestPublisher, filter gatewayx.RouteFilter, modules ...ServiceModule) error

PublishServiceGatewayRoutesWithFilter is the backend-neutral route publishing path. The legacy etcd RouteRegistry path is available through gatewayx.NewRouteRegistryPublisher(registry); Gateway API publication uses gatewayx.NewGatewayAPIPublisher(sink, opts).

func RegisterGRPCServices added in v0.2.4

func RegisterGRPCServices(srv *transportgrpc.Server, bindings ...ServiceBinding) error

func RegisterGatewayInvokers added in v0.2.4

func RegisterGatewayInvokers(registry *gatewayx.InvokerRegistry, bindings ...GatewayBinding) error

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 RegisterHTTPServices added in v0.2.4

func RegisterHTTPServices(srv *transporthttp.Server, bindings ...ServiceBinding) error

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

func New(ctx context.Context, cfg Config, opts ...Option) (*App, error)

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

func NewWithDefaultGovernance(ctx context.Context, cfg Config, opts ...Option) (*App, error)

NewWithDefaultGovernance is a convenience constructor for demos and early services. Production services should pass explicit autowire options once providers are configured.

func (*App) Config

func (a *App) Config() Config

func (*App) DB

func (a *App) DB() dbx.DB

func (*App) Data

func (a *App) Data() any

func (*App) GRPC

func (a *App) GRPC() *transportgrpc.Server

func (*App) HTTP

func (a *App) HTTP() *transporthttp.Server

func (*App) KernelApp

func (a *App) KernelApp() *kernel.App

func (*App) Run

func (a *App) Run() error

type AuditConfig

type AuditConfig struct {
	Enabled  bool
	Provider string
}

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

func LoadConfig(c configx.Config) (Config, error)

LoadConfig loads serverx.Config from an already initialized configx.Config.

func LoadConfigFile

func LoadConfigFile(path string) (Config, error)

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 GRPCConfig

type GRPCConfig struct {
	Enabled bool
	Address string
	Timeout time.Duration
}

type GatewayBinding added in v0.2.4

type GatewayBinding struct {
	Module ServiceModule
	Client any
}

GatewayBinding pairs one generated service module with its generated upstream client. Kernel uses the generated module registration hook to bind Gateway operations to the invoker registry.

type HTTPConfig

type HTTPConfig struct {
	Enabled bool
	Address string
	Timeout time.Duration
}

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 WithKernelOptions(opts ...kernel.Option) Option

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 ProviderRefConfig struct {
	Provider string
	Required bool
}

type RuntimeProviders

type RuntimeProviders struct {
	// Security is the preferred config-derived runtime produced by
	// securityx.NewRuntime. It supplies AuthnBoundary and SkipPolicyResolver while
	// leaving middleware order to serverx/autowire.
	Security *securityx.Runtime

	Access accessx.Providers

	// AccessGuard allows existing services that already own an accessx.Guard to
	// join the unified serverx/autowire path without rebuilding Providers.
	// Prefer Access for new code.
	AccessGuard *accessx.Guard

	// AccessResolver is normally generated from proto access policy. It maps a
	// request operation to an accessx.Check consumed by accessx.Guard.
	AccessResolver accessmw.Resolver

	// SkipPolicyResolver is an optional config-driven skip policy resolver.
	// securityx.Runtime normally supplies this from security.access. This field
	// is kept for tests and advanced overrides.
	SkipPolicyResolver accessmw.SkipPolicyResolver

	// 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,
	// token, API key, or other extraction strategies.
	CredentialExtractor authnmw.CredentialExtractor
	AllowAnonymous      bool

	// AuthnBoundary is the explicit automatic authn wiring object. Prefer setting
	// Security to the result of securityx.NewRuntime so authn and access skip
	// policy come from the same config subtree.
	AuthnBoundary *securityx.AuthnBoundaryRuntime
}

RuntimeProviders is the provider-neutral server wiring contract used by Kernel services. Concrete engines such as Casdoor and SpiceDB must be adapted into provider-neutral Kernel interfaces 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 ServiceBinding added in v0.2.4

type ServiceBinding struct {
	Module         ServiceModule
	Implementation any
}

ServiceBinding pairs one generated service module with its concrete service implementation. Kernel uses the generated module registration hooks to bind the implementation to managed HTTP/RPC transports.

type ServiceCatalog added in v0.2.4

type ServiceCatalog struct {
	// contains filtered or unexported fields
}

ServiceCatalog is the Kernel-owned composition boundary for generated service modules.

Business services should declare their generated modules once and then use the catalog for Gateway route registration, request-info resolution and access resolution. This prevents each service from maintaining separate hand-written module lists for routes and middleware.

func MustServiceCatalog added in v0.2.4

func MustServiceCatalog(modules ...ServiceModule) ServiceCatalog

MustServiceCatalog is for package-level generated catalogs.

func NewServiceCatalog added in v0.2.4

func NewServiceCatalog(modules ...ServiceModule) (ServiceCatalog, error)

NewServiceCatalog validates and stores generated service modules.

func (ServiceCatalog) AccessResolver added in v0.2.4

func (c ServiceCatalog) AccessResolver(ctx context.Context, operation string, req any) (accessx.Check, bool, error)

func (ServiceCatalog) Modules added in v0.2.4

func (c ServiceCatalog) Modules() []ServiceModule

func (ServiceCatalog) PublishGatewayRoutes added in v0.2.4

func (c ServiceCatalog) PublishGatewayRoutes(ctx context.Context, publisher gatewayx.ManifestPublisher) error

PublishGatewayRoutes publishes the catalog's generated Gateway manifests through a provider-neutral ManifestPublisher. Use this when the route control plane may be etcd, Kubernetes Gateway API, GitOps, or another backend.

func (ServiceCatalog) PublishGatewayRoutesWithFilter added in v0.2.4

func (c ServiceCatalog) PublishGatewayRoutesWithFilter(ctx context.Context, publisher gatewayx.ManifestPublisher, filter gatewayx.RouteFilter) error

PublishGatewayRoutesWithFilter applies a deployment profile filter before publishing routes through the selected backend.

func (ServiceCatalog) RegisterGatewayRoutes added in v0.2.4

func (c ServiceCatalog) RegisterGatewayRoutes(ctx context.Context, registry gatewayx.RouteRegistry) error

func (ServiceCatalog) RegisterGatewayRoutesWithFilter added in v0.2.4

func (c ServiceCatalog) RegisterGatewayRoutesWithFilter(ctx context.Context, registry gatewayx.RouteRegistry, filter gatewayx.RouteFilter) error

func (ServiceCatalog) RequestInfoResolver added in v0.2.4

func (c ServiceCatalog) RequestInfoResolver(ctx context.Context, operation string, req any) (requestx.Info, bool, error)

func (ServiceCatalog) RuntimeProviders added in v0.2.4

func (c ServiceCatalog) RuntimeProviders(base RuntimeProviders) RuntimeProviders

type ServiceDeps

type ServiceDeps struct {
	Config    Config
	DB        dbx.DB
	Data      any
	Providers accessx.Providers
}

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

type SystemRoutesConfig struct {
	Enabled bool
	Healthz bool
	Readyz  bool
	Version bool
	Metrics bool
}

SystemRoutesConfig controls generic server routes owned by Kernel, not by business proto.

type SystemRoutesFileConfig

type SystemRoutesFileConfig struct {
	Enabled bool `json:"enabled" yaml:"enabled"`
	Healthz bool `json:"healthz" yaml:"healthz"`
	Readyz  bool `json:"readyz" yaml:"readyz"`
	Version bool `json:"version" yaml:"version"`
	Metrics bool `json:"metrics" yaml:"metrics"`
}

Jump to

Keyboard shortcuts

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