ezboot

package module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: GPL-3.0 Imports: 24 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ezboot

Distributed Go services with a lifecycle you can reason about.

Go 1.27 Release License

English · 简体中文

ezboot is a Go framework for building distributed services. Everything that makes up a process — the HTTP server, the gRPC server, MySQL, Redis, Kafka, OpenTelemetry — is a plugin implementing the same five methods. A small state machine starts them concurrently, waits until they are actually ready, and on shutdown drains and closes them in reverse order.

[!WARNING] ezboot is pre-1.0 (v0.5.x): public APIs may still change between minor releases.

Why ezboot

  • A lifecycle, not just a server. Startup is a state machine with phases, budgets and rollback: a plugin that never becomes ready fails the boot instead of half-serving traffic, and /readyz flips to 503 before in-flight work is drained.
  • Explicit assembly. There is no global container. Dependencies are wired at compile time with wire, and the shutdown order is the reverse of the list you wrote by hand — visible in one file instead of hidden in framework internals.
  • Batteries included, opt-in. HTTP, gRPC with a gateway, six infrastructure plugins, tracing, RBAC and code generation ship in the box, but importing the framework does not open a Redis connection. You register the plugins you actually run.

The whole contract is five methods:

type Plugin interface {
	Name() string
	Start(ctx context.Context) error // blocks until the plugin has stopped
	Ready(ctx context.Context) error // "can this instance take traffic?" — startup only
	Drain(ctx context.Context) error // stop accepting work, wait for in-flight work
	Close(ctx context.Context) error // release resources
}

Embed PluginBase to inherit no-op Ready/Drain/Close, then override only the phases you care about.

Requirements

  • Go 1.27 or newer
  • Docker, only for the code-generation targets (make protobuf, make wire)

Install

go get github.com/ez4bk/ezboot

# project generator
go install github.com/ez4bk/ezboot/cmd/ezboot@latest

Quickstart

Scaffold a service from ezboot-template:

ezboot new demo
cd demo

The command asks for a Go module prefix first (for example github.com/you), then writes it into every import path and into go.work. The generated service enables the MySQL and Redis plugins, so start those first (see config/local.yml for the addresses and credentials it expects):

docker run -d --name demo-mysql -p 3306:3306 \
  -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=demo \
  -e MYSQL_USER=user -e MYSQL_PASSWORD=password mysql:8
docker run -d --name demo-redis -p 6379:6379 redis:7

Run it, then check readiness:

go run ./cmd/demo
curl -s localhost:8899/readyz   # {"status":"OK"}

/readyz answers 503 until every plugin's Ready has passed, and again the moment draining starts. /_healthy is liveness only — it is answered by the process, never by a plugin.

Core concepts

Concept What it is
Plugin A component with a lifecycle: Start, Ready, Drain, Close, Name.
PluginBase Defaults for all five methods: Start blocks on the context, the rest are no-ops.
State Two atomic flags (started, draining) written by the lifecycle and read by /readyz. Runtime readiness never probes plugins.
Application ezboot.NewApp(...) plus options (WithPlugins, WithState, WithLifecycleConfig, WithCmdline). Start(ctx) returns only after drain and close have finished.
ProviderSet The wire set for dependencies that every service needs and nobody customizes.
Lifecycle The internal state machine that drives the plugins. Not exported; you observe it through Application and State.

Assembly with wire

ezboot assumes google/wire as its dependency injection mechanism, and that assumption is part of the design rather than an implementation detail:

  • Compile-time graph. Missing providers are build errors, not runtime panics. There is no service locator to fall back on.
  • Construction order is dependency order. The tracer provider must exist before a gRPC server is built (interceptors are read when the driver is constructed), so wiring it as a constructor argument is what actually enforces the order.
  • Nothing is auto-registered. A plugin runs because you put it in the list — not because a blank import did something.

ezboot.ProviderSet covers only what is universal and non-negotiable:

var ProviderSet = wire.NewSet(
	ProvideConfig,        // config + telemetry init
	ProvideLogger,
	NewState,
	tracing.NewOTEL,
	grpcclient.NewGRPCClient,
)

HTTP, gRPC and the six infrastructure plugins are deliberately excluded. They need application-specific inputs (routes, service registrations, gateway handlers), and wire has no same-type multi-binding: putting grpc.New in the shared set collides with the application's own constructor.

One function must close []ezboot.Plugin, and its argument order is the shutdown order:

func NewPlugins(
	otel *tracing.OTEL,
	db *infra.Databases,
	gc *grpcclient.GRPCClient,
	gs *grpc.Server,
	hs *http.Server,
) []ezboot.Plugin {
	// Closed in reverse: http → grpc → grpc-client → db → otel
	return []ezboot.Plugin{otel, db, gc, gs, hs}
}

Adding a plugin therefore means changing this signature and regenerating (wire ./...; the template wraps it in make wire). That friction is intentional: it keeps the composition root reviewable in a diff.

Lifecycle

Start (concurrent)
  → poll Ready          until all pass, or ready_timeout expires
  → started
  → wait for signal
  → draining            /readyz starts answering 503
  → Drain (reverse, serial)   stop accepting work, wait for in-flight work
  → cancel Start ctx
  → Close (reverse, serial)   release resources
  • Start runs concurrently, so boot time is the slowest plugin, not the sum. A Start that returns before shutdown is a crash and tears the application down.
  • Ready is polled, every 100 ms with each attempt capped at 2 s, until all plugins pass or ready_timeout expires. A failed boot rolls back: the remaining plugins are cancelled and everything already started is closed.
  • Drain then Close, each in reverse registration order, each with its own fresh timeout context. They are not interchangeable: Drain stops accepting work and waits for in-flight work; Close releases resources.
  • Order matters. Registration order is shutdown order: infrastructure first (closed last), entry points last (closed first), and OpenTelemetry at the very top so it flushes spans after everything else has stopped.

Budgets are configured under app.lifecycle; zero values fall back to the defaults shown:

app:
  lifecycle:
    ready_timeout: 10s   # per plugin, startup
    drain_timeout: 10s   # per plugin
    close_timeout: 5s    # per plugin

In Kubernetes, keep terminationGracePeriodSeconds larger than the sum of the drain and close budgets, plus margin.

Plugins

Plugin Package Responsibility Ready means
HTTP http gin engine, middleware, pprof, optional /metrics, /_healthy, /readyz listener is bound
gRPC grpc server, gateway handler, reflection, Prometheus, graceful stop listener bound, gateway ready
gRPC client pool grpc/client process-wide client connections, created on first use always (connections are lazy)
OpenTelemetry tracing tracer provider, interception, span flush on close always
Databases infra MySQL, SQLite or PostgreSQL through xorm — exactly one dialect per process all configured pools ping
Redis infra clients per named instance ping
Kafka infra brokers, readers and writers per topic broker reachable
RabbitMQ infra connection with a reconnect loop channel available
Elasticsearch infra search client ping
Etcd infra client v3 endpoint reachable

Each infrastructure plugin ships its own ProviderSet with a default provider, so business code depends on the native type (*xorm.Engine, *redis.Client) rather than on a framework abstraction.

Writing your own plugin is the same five methods: embed PluginBase, implement Name and the phases you need, and add it to NewPlugins. Constructors may create client objects but must not perform network I/O or bind ports — that belongs in Start, and Ready is where a dependency is proven usable. The template includes a complete example under internal/plugin/example.

Batteries

Package Purpose
rbac Casbin-based RBAC model, policy definitions and loading
exorm xorm query helpers: conditions, pagination, cursor pagination
bizerr Business error type with gRPC status and gateway mapping
snowflake Snowflake ID generation
retry Exponential and constant retry built on backoff
cache Redis-backed cache for binary-marshalable values
flight Generic singleflight duplicate suppression
exp Generic helpers: lazy values, maps, extraction, AES/RSA
xjson JSON helpers
xref Reflection helpers
elog Log-and-wrap error helpers
utils Pointer and string utilities
signal SIGINT/SIGTERM context via signal.WithExit
with Access to the default engine and Redis handle registered by plugins

Tooling

Tool Purpose
ezboot new Scaffold a service from the template repository
ezboot model Generate model definitions from an existing database schema
protoc-gen-go-ezboot Protobuf generator for ezboot service glue
protoc-gen-go-rbac Protobuf generator for RBAC definitions
make protobuf Run buf generate in the pinned container image
tools/reflect DAO generation from model structs
cmd/snowflake Standalone Snowflake ID generator

Documentation

  • Wiki — technical details and architecture decision records (Chinese)
  • ezboot-template — reference service: wiring, a custom plugin, Helm chart

Documentation

Index

Constants

View Source
const (
	// Version 当前框架的版本
	Version = "v0.5.1"
)

Variables

View Source
var (
	// ErrNotStarted 表示应用还没有完成启动,不应接收流量。
	ErrNotStarted = errors.New("ezboot: not started")
	// ErrDraining 表示应用正在排空,不应接收新流量。
	ErrDraining = errors.New("ezboot: draining")
	// ErrNilState 表示调用方传入了一个 nil 的就绪状态对象。
	ErrNilState = errors.New("ezboot: state is nil")
)
View Source
var DiscardLogger = zap.NewNop().Sugar()

DiscardLogger 是一个默认的空输出的日志记录器

View Source
var ErrNilConfig = errors.New("ezboot: config is nil")

ErrNilConfig 表示调用方传入了一个 nil 的框架配置。

View Source
var ErrNilMigrationFS = errors.New("ezboot: migrations fs is nil")

ErrNilMigrationFS 表示调用方传入了一个 nil 的迁移文件系统。

ProviderSet 提供所有应用都会用到、且不需要定制的依赖与插件:

配置 + 日志 + 就绪状态 + tracing + gRPC 客户端连接池

http 与 grpc 插件刻意不在这里:它们需要路由、service 注册、网关等 应用特有的参数,必须由应用自己的 provider 构造。把 grpc.New / http.New 放进这个集合会与应用的构造器产生同类型冲突(wire: multiple bindings)。

infra 插件(MySQL / Redis / Kafka / RabbitMQ / Elasticsearch / Etcd) 也不在这里:只用 HTTP 的服务不应该因为引入框架就打开 Redis。

Functions

func CloseClients added in v0.5.0

func CloseClients() error

CloseClients closes every cached gRPC client connection.

func Env

func Env() string

func GetClient added in v0.5.0

func GetClient(name string) (*grpc.ClientConn, error)

GetClient returns the cached gRPC connection configured under name.

func InjectGrpcClient

func InjectGrpcClient(v any)

func IsLocal

func IsLocal() bool

func IsProd

func IsProd() bool

func LoadUserConfig

func LoadUserConfig(cfg any) error

LoadUserConfig 加载用户配置

func LoggerLevel

func LoggerLevel() string

func RegisterClient

func RegisterClient(serverKind string, newFunc interface{})

Types

type Application

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

Application 是一个gin-boot应用程序

func NewApp

func NewApp(options ...ApplicationOption) (*Application, error)

NewApp 创建一个应用

func (*Application) Start

func (app *Application) Start(ctx context.Context) error

Start 启动gin-boot应用

type ApplicationOption

type ApplicationOption func(app *Application) error

ApplicationOption 创建应用的额外选项

func WithAppName

func WithAppName(name string) ApplicationOption

WithAppName 设置应用名字

func WithCmdline

func WithCmdline(cmdline ...*cobra.Command) ApplicationOption

WithCmdline 增加一个额外命令行配置项

func WithGrpcServer deprecated

func WithGrpcServer(gs *grpc.Server) ApplicationOption

WithGrpcServer 设置启动Grpc服务。

Deprecated: 使用 WithPlugins 显式注册插件。

func WithHttpServer deprecated

func WithHttpServer(hs *http.Server) ApplicationOption

WithHttpServer 设置启动Http服务。

Deprecated: 使用 WithPlugins 显式注册插件。

func WithLifecycleConfig added in v0.5.0

func WithLifecycleConfig(cfg *Config) ApplicationOption

WithLifecycleConfig 从框架配置读取生命周期各阶段的预算 (app.lifecycle.*),零值使用默认值。

func WithMigrations added in v0.5.2

func WithMigrations(fsys fs.FS) ApplicationOption

WithMigrations 注入应用内嵌的迁移文件系统(通常来自 //go:embed)。 文件系统的根目录必须直接包含 *.up.sql / *.down.sql 迁移文件。 开启自动迁移但没有调用本选项时,启动会失败。

func WithPluginTimeouts added in v0.5.0

func WithPluginTimeouts(ready, drain, close time.Duration) ApplicationOption

WithPluginTimeouts 覆盖生命周期各阶段的默认预算。

func WithPlugins added in v0.5.0

func WithPlugins(plugins ...Plugin) ApplicationOption

WithPlugins 注册参与生命周期的插件。列表顺序决定 Close 的逆序: 越靠前的插件越晚关闭(例如 OTEL 应放在最前)。

func WithStartPreHook

func WithStartPreHook(hook func(context.Context) error) ApplicationOption

WithStartPreHook 在服务启动之前的任务

func WithState added in v0.5.0

func WithState(state *State) ApplicationOption

WithState 设置就绪状态对象。它与 HTTP 插件共享,由 lifecycle 写入。

type Config

type Config = config.Config

Config 配置别名

func ProvideConfig

func ProvideConfig() *Config

ProvideConfig 加载框架全局配置。

它同时完成需要早于插件构造的初始化(tracing 拦截器、gRPC 客户端池), 因为 gRPC driver 在构造时就会读取拦截器列表。

type Logger

type Logger = zap.SugaredLogger

Logger 日志实现的别名

func ProvideLogger

func ProvideLogger() *Logger

ProvideLogger 加载日志记录器。它先确保配置已加载,因此和 ProvideConfig 之间没有隐式的构造顺序要求。

type Plugin added in v0.5.0

type Plugin interface {
	Name() string
	Start(ctx context.Context) error
	Ready(ctx context.Context) error
	Drain(ctx context.Context) error
	Close(ctx context.Context) error
}

Plugin 是应用生命周期中一个可插拔的组件。

阶段调用顺序:Start → 轮询 Ready → Drain → Close。

契约:

  • Start 必须阻塞到插件停止(覆盖它时记得自己写 <-ctx.Done())。 Start 返回即代表插件已经停止。
  • Ready 回答“现在能不能接流量”,只在启动期被调用。它必须便宜、 可重复调用、并发安全,不得自己重试或长时间阻塞。
  • Drain 与 Close 收到的是 lifecycle 新建的、带超时的 ctx,不是 Start 时的那个。Drain 负责停止接收新工作并等待在途工作结束, Close 负责释放资源。两者不可合并。
  • Name 只用于日志与错误信息,不作为查找键。

type PluginBase added in v0.5.0

type PluginBase struct{}

PluginBase 提供四个阶段的默认实现。嵌入它之后,插件只需要实现 Name,以及自己真正关心的那几个阶段。

func (PluginBase) Close added in v0.5.0

Close 默认什么都不做。

func (PluginBase) Drain added in v0.5.0

Drain 默认什么都不做。

func (PluginBase) Ready added in v0.5.0

Ready 默认认为插件随时可用。有连接语义的插件必须覆盖它。

func (PluginBase) Start added in v0.5.0

func (PluginBase) Start(ctx context.Context) error

Start 阻塞到 ctx 结束。这是有意为之:Start 返回就代表插件已经停止, lifecycle 依靠这个信号判断插件是否还活着。

type ServerType

type ServerType = grpc_boot.ServerType

type State added in v0.5.0

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

State 是就绪状态的唯一数据源:由 lifecycle 写入,由就绪端点读取。

运行期的 /readyz 只读它,不去探测任何插件。依赖故障交给超时、重试 与熔断处理;readiness 只回答“这个实例该不该接流量”。

func NewState added in v0.5.0

func NewState() *State

NewState 创建一个就绪状态对象。

func (*State) Draining added in v0.5.0

func (s *State) Draining() bool

Draining 报告是否正在排空。

func (*State) MarkDraining added in v0.5.0

func (s *State) MarkDraining()

MarkDraining 标记开始排空。调用后 /readyz 立即返回 503。

func (*State) MarkStarted added in v0.5.0

func (s *State) MarkStarted()

MarkStarted 标记启动完成。由 lifecycle 在全部插件 Ready 之后调用。

func (*State) Ready added in v0.5.0

func (s *State) Ready() error

Ready 返回应用当前是否可以接收流量。它可以直接作为 /readyz 的实现。

func (*State) Started added in v0.5.0

func (s *State) Started() bool

Started 报告启动是否已完成。

Directories

Path Synopsis
cmd
snowflake command
ezboot module
client
Package client 把进程级 gRPC 客户端连接池暴露成一个插件。
Package client 把进程级 gRPC 客户端连接池暴露成一个插件。
Package infra 把外部依赖封装成插件:数据库、Redis、消息队列、搜索 和 etcd。
Package infra 把外部依赖封装成插件:数据库、Redis、消息队列、搜索 和 etcd。
internal
gin-boot/middleware
Package middleware contains HTTP and gRPC request-pipeline middleware only: logging, recovery, validation, metadata helpers and tracing interceptors.
Package middleware contains HTTP and gRPC request-pipeline middleware only: logging, recovery, validation, metadata helpers and tracing interceptors.
logging
Package logging 1.
Package logging 1.
Package snowflake provides a very simple Twitter snowflake generator and parser.
Package snowflake provides a very simple Twitter snowflake generator and parser.
tools
reflect module
Package tracing 把 OpenTelemetry 的 tracer provider 暴露成一个插件。
Package tracing 把 OpenTelemetry 的 tracer provider 暴露成一个插件。

Jump to

Keyboard shortcuts

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