kernel

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 17 Imported by: 0

README

Aisphere Kernel

Aisphere Kernel 是 Aisphere 项目的规范驱动微服务基础框架。

核心原则:业务声明契约,Kernel 负责检查、生成、装配、治理和验证。业务项目优先写 proto contract 和领域逻辑,不手写 transport glue、错误协议转换、访问控制、审计、限流或 Gateway 分发。

Quick start

go install github.com/aisphereio/kernel/cmd/kernel@latest
kernel version
kernel new todo-service
cd todo-service
make tools
make api
make proto-check
make verify
make run

最小可运行服务:

kernel new todo-service --mvp

裁剪能力:

kernel new todo-service --disable iam,gateway,dtmx

--repo 只作为高级覆盖项,用于本地模板、私有 layout 或测试 layout 分支。

Runtime API

业务代码和生成代码可以 import:

errorx logx configx metricsx serverx
transportx/http transportx/grpc
requestx accessx authn authz auditx
gatewayx admissionx ratelimitx clientpolicyx
dbx cachex objectstorex dtmx
selectorx registry encodingx

Development tooling

这些是工具,不是 runtime API。业务代码不能 import:

cmd/kernel
cmd/protoc-gen-go-http
cmd/protoc-gen-go-errors
cmd/protoc-gen-go-authz
cmd/protoc-gen-go-gateway
cmd/protoc-gen-go-kernel
cmd/buf-check-aisphere

生成项目通过 make tools 安装工具链。

Removed / not mainline

validation/                 removed; scenario checks must not live in runtime tree
middleware/ratelimit/       removed; use ratelimitx
internal/ratelimit/         removed; use ratelimitx providers
github.com/aisphereio/kernel/errors removed; use errorx
core/httpx/contextx as main docs wording obsolete; use serverx/transportx/requestx/accessx
grpcgatewayx                not mainline; use grpc-gateway generator, protoc-gen-go-gateway and gatewayx

Proto-first development

proto contract
  -> buf-check-aisphere
  -> protoc generators
  -> requestx.Info / accessx / gatewayx / serverx
  -> business service implementation

Full profile 的外部 RPC 必须声明 google.api.httpaisphere.access.v1.policy--mvp 只用于最小可运行骨架。

Verify

make tools
make api
make test
make test-cmd
make vet

完整本地门禁:

make verify

Documentation

Documentation

Overview

Package kernel provides the lifecycle root for Aisphere Kernel.

Kernel is a specification-driven microservice foundation. Business projects declare contracts in proto; Kernel tools check and generate runtime glue; and Kernel runtime packages provide fixed infrastructure for service assembly, request metadata, access control, traffic governance, observability and errors.

Main runtime surfaces:

  • configx: configuration loading and scanning
  • logx: structured logging
  • metricsx: metrics manager
  • errorx: cross-protocol business errors
  • serverx: service assembly and runtime autowire
  • transportx/http and transportx/grpc: HTTP and gRPC transports
  • requestx: request metadata shared by middleware and business logic
  • accessx, authn, authz and auditx: identity, authorization and audit
  • gatewayx: route manifests, route registries and gateway dispatch
  • admissionx: mutating and validating admission chains
  • ratelimitx and clientpolicyx: traffic governance contracts
  • dbx, cachex, objectstorex and dtmx: data and transaction integrations

Development tools live under cmd/. Business code must not import cmd/kernel, cmd/protoc-gen-* or cmd/buf-check-* packages directly.

Scenario validation code was intentionally removed from the runtime tree. Add future scenario checks in a dedicated repository, behind explicit build tags, or as generated-layout tests rather than as framework runtime packages.

Index

Constants

View Source
const Release = "v0.0.0-baseline"

Release is the current kernel version.

Variables

This section is empty.

Functions

func DTMFromContext added in v0.1.10

func DTMFromContext(ctx context.Context) dtmx.Manager

DTMFromContext returns the distributed transaction manager injected by kernel.App, or a disabled manager when DTM is not configured.

func MetricsFromContext added in v0.0.6

func MetricsFromContext(ctx context.Context) metricsx.Manager

MetricsFromContext returns the metrics manager injected by kernel.App, or a no-op manager when metrics are disabled. This keeps lifecycle hooks and component setup code independent from the concrete metrics package bootstrap.

func NewContext

func NewContext(ctx context.Context, s AppInfo) context.Context

NewContext returns a new Context that carries value.

Types

type App

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

App is an application components lifecycle manager.

func New

func New(opts ...Option) *App

New create an application lifecycle manager.

func (*App) Endpoint

func (a *App) Endpoint() []string

Endpoint returns endpoints.

func (*App) ID

func (a *App) ID() string

ID returns app instance id.

func (*App) Metadata

func (a *App) Metadata() map[string]string

Metadata returns service metadata.

func (*App) Name

func (a *App) Name() string

Name returns service name.

func (*App) Run

func (a *App) Run() error

Run executes all OnStart hooks registered with the application's Lifecycle.

func (*App) Stop

func (a *App) Stop() (err error)

Stop gracefully stops the application.

func (*App) Version

func (a *App) Version() string

Version returns app version.

type AppInfo

type AppInfo interface {
	ID() string
	Name() string
	Version() string
	Metadata() map[string]string
	Endpoint() []string
}

AppInfo is application context value.

func FromContext

func FromContext(ctx context.Context) (s AppInfo, ok bool)

FromContext returns the Transport value stored in ctx, if any.

type Option

type Option func(o *options)

Option is an application option.

func AfterStart

func AfterStart(fn func(context.Context) error) Option

AfterStart run funcs after app starts

func AfterStop

func AfterStop(fn func(context.Context) error) Option

AfterStop run funcs after app stops

func BeforeStart

func BeforeStart(fn func(context.Context) error) Option

BeforeStart run funcs before app starts

func BeforeStop

func BeforeStop(fn func(context.Context) error) Option

BeforeStop run funcs before app stops

func Context

func Context(ctx context.Context) Option

Context with service context.

func DTM added in v0.0.9

func DTM(manager dtmx.Manager) Option

DTM installs a shared distributed transaction manager before lifecycle hooks or transport servers start. The manager is injected into kernel contexts so hooks and business bootstrap code can call kernel.DTMFromContext(ctx) without importing a concrete DTM implementation.

func Endpoint

func Endpoint(endpoints ...*url.URL) Option

Endpoint with service endpoint.

func ID

func ID(id string) Option

ID with service id.

func Logger

func Logger(logger *slog.Logger) Option

Logger installs the application's slog logger before any lifecycle hooks or transport servers start. It also becomes logx's package default so lower-level components initialized by hooks can write to the same sink.

func LogxLogger added in v0.0.5

func LogxLogger(logger logx.Logger) Option

LogxLogger installs the application's logx logger before any lifecycle hooks or transport servers start. Prefer this option for new Kernel applications so dbx/cachex/authn/authz/objectstorex can share the same logger without depending on slog directly.

func Metadata

func Metadata(md map[string]string) Option

Metadata with service metadata.

func Metrics added in v0.0.6

func Metrics(manager metricsx.Manager) Option

Metrics installs a shared metrics manager before lifecycle hooks or transport servers start. The manager is injected into kernel contexts so hooks can call metricsx.FromContext(ctx) and pass the same manager into dbx/cachex/s3/authn/authz.

func MetricsPath added in v0.0.6

func MetricsPath(path string) Option

MetricsPath changes the admin metrics path used by PrometheusMetrics. Empty or malformed values fall back to /metrics.

func MetricsPprof added in v0.0.6

func MetricsPprof(enabled bool) Option

MetricsPprof controls whether kernel's built-in metrics admin server also exposes /debug/pprof/*. It is disabled by default to avoid exposing profiling endpoints unintentionally in production.

func MetricsSystem added in v0.0.6

func MetricsSystem(enabled bool) Option

MetricsSystem controls whether standard Go runtime metrics are registered. It defaults to true when Metrics or PrometheusMetrics is used.

func Name

func Name(name string) Option

Name with service name.

func PrometheusMetrics added in v0.0.6

func PrometheusMetrics(addr string) Option

PrometheusMetrics creates a Prometheus-backed metrics manager during kernel.New and optionally exposes it on a small admin HTTP server. Pass an empty addr to create and inject the manager without starting an extra server.

Typical production setup:

app := kernel.New(
    kernel.Name("aihub"),
    kernel.Version(version),
    kernel.PrometheusMetrics(":9090"), // GET http://127.0.0.1:9090/metrics
)

func Registrar

func Registrar(r registry.Registrar) Option

Registrar with service registry.

func RegistrarTimeout

func RegistrarTimeout(t time.Duration) Option

RegistrarTimeout with registrar timeout.

func Server

func Server(srv ...transport.Server) Option

Server with transport servers.

func Signal

func Signal(sigs ...os.Signal) Option

Signal with exit signals.

func StopTimeout

func StopTimeout(t time.Duration) Option

StopTimeout with app stop timeout.

func Version

func Version(version string) Option

Version with service version.

Directories

Path Synopsis
Package accessx provides a small authn + authz + audit facade for handlers.
Package accessx provides a small authn + authz + audit facade for handlers.
Package admissionx implements Kubernetes-style mutating and validating admission chains.
Package admissionx implements Kubernetes-style mutating and validating admission chains.
api
Package auditx defines durable audit recording contracts.
Package auditx defines durable audit recording contracts.
Package authn cached.go — cache decorator for Authenticator + TokenService.
Package authn cached.go — cache decorator for Authenticator + TokenService.
callback
Package callback contains reusable HTTP helpers for browser based authn callback flows.
Package callback contains reusable HTTP helpers for browser based authn callback flows.
casdoor
Package casdoor adapts the official Casdoor Go SDK to Kernel authn contracts.
Package casdoor adapts the official Casdoor Go SDK to Kernel authn contracts.
Package authz defines Kernel's authorization boundary.
Package authz defines Kernel's authorization boundary.
spicedb
Package spicedb contains SpiceDB adapter contracts and configuration for authz.
Package spicedb contains SpiceDB adapter contracts and configuration for authz.
Package bootx owns framework-level startup validation.
Package bootx owns framework-level startup validation.
Package cachex provides the unified cache API for Aisphere Kernel.
Package cachex provides the unified cache API for Aisphere Kernel.
redis
Package redis registers the "redis" driver for cachex.
Package redis registers the "redis" driver for cachex.
Package clientpolicyx defines outbound microservice call governance.
Package clientpolicyx defines outbound microservice call governance.
cmd
kernel command
kernel/internal/project/templates command
Package main is a reference handler template showing correct errorx usage.
Package main is a reference handler template showing correct errorx usage.
Package configx provides the unified configuration API for Aisphere Kernel.
Package configx provides the unified configuration API for Aisphere Kernel.
env
Package contextx provides business-facing request context utilities for Aisphere Kernel.
Package contextx provides business-facing request context utilities for Aisphere Kernel.
Package dbrepo provides opinionated repository helpers on top of dbx.
Package dbrepo provides opinionated repository helpers on top of dbx.
dbx
Package dbx provides the unified, batteries-included database API for Aisphere Kernel.
Package dbx provides the unified, batteries-included database API for Aisphere Kernel.
mysql
Package mysql registers the "mysql" driver for dbx.
Package mysql registers the "mysql" driver for dbx.
postgres
Package postgres registers the "postgres" driver for dbx.
Package postgres registers the "postgres" driver for dbx.
Package dtmx defines Kernel's distributed transaction abstraction.
Package dtmx defines Kernel's distributed transaction abstraction.
dtm
Package dtm registers the dtm-labs/dtm implementation for dtmx.
Package dtm registers the dtm-labs/dtm implementation for dtmx.
proto
Package proto defines the protobuf codec.
Package proto defines the protobuf codec.
xml
Package errorx defines Aisphere Kernel's shared error semantics.
Package errorx defines Aisphere Kernel's shared error semantics.
examples
authn-casdoor command
Command authn-casdoor exercises Kernel authn against a real local Casdoor.
Command authn-casdoor exercises Kernel authn against a real local Casdoor.
authz-spicedb command
Command authz-spicedb exercises Kernel authz against a real local SpiceDB.
Command authz-spicedb exercises Kernel authz against a real local SpiceDB.
cachex-basic command
Package main demonstrates basic cachex usage with Redis.
Package main demonstrates basic cachex usage with Redis.
configx-basic command
configx-env command
Package main demonstrates configx layered file + env override.
Package main demonstrates configx layered file + env override.
configx-watch command
Package main demonstrates configx Watch hot reload.
Package main demonstrates configx Watch hot reload.
contextx-basic command
Package main demonstrates contextx basic usage.
Package main demonstrates contextx basic usage.
dbx-basic command
Package main demonstrates the basic dbx flow with Postgres, mirroring aisphere-hub's skill.go patterns.
Package main demonstrates the basic dbx flow with Postgres, mirroring aisphere-hub's skill.go patterns.
dbx-scenarios command
Package main is a comprehensive scenario validator for dbx.
Package main is a comprehensive scenario validator for dbx.
dtmx-saga command
errorx-basic command
errorx-http command
Package main demonstrates a complete HTTP handler that returns errorx errors.
Package main demonstrates a complete HTTP handler that returns errorx errors.
gatewayx-basic command
logx-basic command
Package main demonstrates logx basic usage.
Package main demonstrates logx basic usage.
logx-http command
Package main demonstrates logx in a complete HTTP server with access log middleware, panic recovery, request-scoped fields, and dynamic level control.
Package main demonstrates logx in a complete HTTP server with access log middleware, panic recovery, request-scoped fields, and dynamic level control.
metricsx-basic command
Package main demonstrates metricsx basic usage.
Package main demonstrates metricsx basic usage.
objectstorex-basic command
Package main demonstrates basic objectstorex usage with Minio.
Package main demonstrates basic objectstorex usage with Minio.
Package gatewayx provides Gateway/BFF building blocks on top of Kernel's existing transportx/http package.
Package gatewayx provides Gateway/BFF building blocks on top of Kernel's existing transportx/http package.
Package grpcgatewayx contains runtime helpers for grpc-gateway generated *.gw.pb.go handlers.
Package grpcgatewayx contains runtime helpers for grpc-gateway generated *.gw.pb.go handlers.
Package grpcx provides Kernel's standard gRPC runtime layer.
Package grpcx provides Kernel's standard gRPC runtime layer.
Package iamx defines Kernel's provider-neutral IAM domain model.
Package iamx defines Kernel's provider-neutral IAM domain model.
authnadapter
Package authnadapter adapts authn.IdentityAdmin providers, such as Casdoor, into Kernel IAM directory contracts.
Package authnadapter adapts authn.IdentityAdmin providers, such as Casdoor, into Kernel IAM directory contracts.
db
internal
group
Package group provides a sample lazy load container.
Package group provides a sample lazy load container.
protooptions
Package protooptions contains low-level parsers for Aisphere protobuf custom options.
Package protooptions contains low-level parsers for Aisphere protobuf custom options.
Package logx is the Aisphere Kernel logging package.
Package logx is the Aisphere Kernel logging package.
Package metricsx provides business-facing metrics for Aisphere Kernel.
Package metricsx provides business-facing metrics for Aisphere Kernel.
access
Package access provides server-side authz/audit middleware built on accessx.
Package access provides server-side authz/audit middleware built on accessx.
authn
Package authn provides transport middleware for Kernel authentication.
Package authn provides transport middleware for Kernel authentication.
autowire
Package autowire assembles Kernel's default middleware pipelines.
Package autowire assembles Kernel's default middleware pipelines.
ctxinject
Package ctxinject injects transport metadata into Kernel request contexts.
Package ctxinject injects transport metadata into Kernel request contexts.
requestinfo
Package requestinfo resolves requestx.Info once near the front of the middleware chain.
Package requestinfo resolves requestx.Info once near the front of the middleware chain.
retry
Package retry provides client-side retry middleware for transient failures.
Package retry provides client-side retry middleware for transient failures.
timeout
Package timeout provides transport-agnostic timeout middleware.
Package timeout provides transport-agnostic timeout middleware.
Package migrationx provides Kernel's SQL migration integration layer.
Package migrationx provides Kernel's SQL migration integration layer.
Package objectstorex provides the unified object storage API for Aisphere Kernel.
Package objectstorex provides the unified object storage API for Aisphere Kernel.
minio
Package minio registers the "minio" driver for objectstorex.
Package minio registers the "minio" driver for objectstorex.
Package ratelimitx defines Kernel's rate limit provider contract.
Package ratelimitx defines Kernel's rate limit provider contract.
Package requestx provides the canonical request metadata model used by Kernel middleware.
Package requestx provides the canonical request metadata model used by Kernel middleware.
Package restx contains go-zero-inspired HTTP runtime helpers for Kernel.
Package restx contains go-zero-inspired HTTP runtime helpers for Kernel.
Package securityx groups external configuration for authn, authz and auditx.
Package securityx groups external configuration for authn, authz and auditx.
p2c
wrr
Package serverx provides Kernel's opinionated service assembly layer.
Package serverx provides Kernel's opinionated service assembly layer.
Package servicecontextx provides a tiny typed dependency container for generated or hand-written service entrypoints.
Package servicecontextx provides a tiny typed dependency container for generated or hand-written service entrypoints.

Jump to

Keyboard shortcuts

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