serverx

package
v0.1.17 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2026 License: MIT Imports: 24 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 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 a generated module's manifest into the route registry. CI/CD or service startup can call this; business code should not handcraft routes.

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, impl any, opts ...BuildOption) (*App, error)

BuildService is the backwards-compatible generated-service boot path for callers that already have a concrete implementation. Prefer BuildServiceFromFactory for new services so Kernel-managed Data/DB/providers are injected after config, migration, and provider loading.

func BuildServiceFromFactory

func BuildServiceFromFactory(ctx context.Context, cfg Config, module ServiceModule, factory ServiceFactory, opts ...BuildOption) (*App, error)

BuildServiceFromFactory is the preferred autoload path: config + generated module + provider factory + business factory. It assembles Kernel middleware automatically, opens DB, runs/validates SQL migrations, constructs generated repositories, creates the concrete service implementation, and registers generated HTTP/gRPC routes.

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

func WithRuntime

func WithRuntime(p RuntimeProviders) BuildOption

func WithServerOptions

func WithServerOptions(opts ...Option) 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 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 {
	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

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