bootstrap

package
v0.9.6 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 32 Imported by: ? 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.

Documentation

Overview

Package bootstrap 把域服务 main() 的固定装配收进框架。

域服务的启动顺序是死的:加载配置 → 初始化遥测 → 建连接池 → 建事件总线 → 装配模块 → 运行 → 反序关停。这段仪式每个域仓库一字不差,却最容易被改坏, 且改坏了框架无从知情——少一个 tel.Shutdown 就丢 span,pool.Close 提前一步 就在关停期查询失败,忘了 Migrator 就静默不跑迁移。

收进这里之后它位于 module cache(0444 只读),改不动也不必读。 用户仓库的 main 只声明"装哪些模块",见 Options。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Main

func Main(o Options)

Main 是域服务 main() 的全部内容:解析 flag、装配、运行; 失败时打印到 stderr 并以退出码 1 结束。

需要自定义 flag 或注入 ctx 时改用 Run。

func MainWithSecurity added in v0.9.1

func MainWithSecurity(o Options, security SecurityOptions)

MainWithSecurity 与 Main 使用相同的运行参数,额外接收由组合根构造的 服务验签器或多用户签发方配置。私钥不属于接收端配置;security.mode 仍须显式声明。

func Run

func Run(ctx context.Context, o Options, r RunOptions) error

Run 执行装配与运行,直到收到关停信号或运行期错误; r.MigrateOnly 为 true 时应用完迁移即返回。

func RunWithSecurity added in v0.9.1

func RunWithSecurity(ctx context.Context, o Options, r RunOptions, security SecurityOptions) error

RunWithSecurity 在连接数据库、模块装配或监听端口前验证安全配置。 internal_service 要求有效 ServiceVerifier;mixed 还要求 Options 的单用户 签发方或 SecurityOptions.UserIssuers。没有凭证的请求只可访问显式公开路由及探针。

Types

type Base

type Base struct {
	Addr     string   `koanf:"addr"`
	Env      string   `koanf:"env" validate:"omitempty,oneof=dev staging prod"`
	Database Database `koanf:"database"`
	Log      Log      `koanf:"log"`
	Debug    Debug    `koanf:"debug"`
}

Base 是每个域服务共有的配置项。需要额外配置项时,用 Deps.Config 再 config.Load 一次自己的结构——同一份文件与环境变量,不必重复声明这些。

type Capabilities added in v0.9.6

type Capabilities struct {
	BusinessHTTP bool
	PostgreSQL   bool
	Bus          bool
	Migrations   bool
}

Capabilities 是新 Bootstrap Profile 可用的进程能力。HTTP 指业务入站 HTTP; Probe 是独立的只读健康/就绪 Listener。Migrations 必须依赖 PostgreSQL。

type Core added in v0.9.6

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

Core 持有单个 Profile 的配置、日志、Telemetry 与可选基础设施。 每个 Core 仅可启动一次;Start 用于嵌入式调用,Execute 执行一次性受管 函数。Core 不安装 OS Signal Handler。

func NewCore added in v0.9.6

func NewCore(ctx context.Context, options ProfileOptions) (*Core, error)

NewCore 加载通用配置并初始化日志/Telemetry,再按显式 capability 打开可选 PostgreSQL 与 Bus。BusinessHTTP 关闭时不会加载或校验 HTTP SecurityMode。

func (*Core) Close added in v0.9.6

func (c *Core) Close(ctx context.Context) error

Close 关闭尚未启动的 Core;若 Host 已启动,则先请求优雅关停。Start 期间 不允许并发 Close,避免资源在装配中途被释放。

func (*Core) Execute added in v0.9.6

func (c *Core) Execute(ctx context.Context, fn func(context.Context, ProfileDeps) error) error

Execute 以无监听、无 OS Signal 的 One-shot Profile 启动 App,执行 fn 后 优雅关停。fn 的错误与关停/Telemetry 错误通过 errors.Join 保留。

func (*Core) Start added in v0.9.6

func (c *Core) Start(ctx context.Context) (*RunningProfile, error)

Start 启动 Profile 并在 Host Ready 后返回;不注册 OS Signal Handler。

type Database

type Database struct {
	// URL 形如 postgres://user:pass@host:5432/db?sslmode=disable。
	// 留空时默认拒绝启动;本地零依赖试跑必须显式传 -minimal。
	// 生产部署必须配置。
	URL string `koanf:"url"`
}

Database 是数据库配置。

type Debug

type Debug struct {
	// Pprof 为 true 时挂 /debug/pprof/*(语义见 appkit.Pprof)。
	Pprof bool `koanf:"pprof"`
}

Debug 是排障端点配置。全部默认关闭:pprof 暴露进程内部信息 (goroutine 栈、堆采样可能含敏感数据),开启前先确认服务端口 不暴露公网或网络策略已挡好。 放配置而不是代码开关:线上排障改 configmap 重启即生效,不必发版。

type Deps

type Deps struct {
	// Log 是已接入 trace 的服务日志器。
	Log *slog.Logger
	// Base 是已加载并填过默认值的框架配置。
	Base Base
	// Pool 是数据库连接池;最小模式下为 nil。
	Pool *pgxpool.Pool
	// Bus 是事件总线;最小模式下为 nil。
	Bus EventBus
	// Config 复现框架加载配置时的入参。需要额外配置项时:
	//   cfg, err := config.Load[myConfig](d.Config)
	Config config.Options
}

Deps 是框架已备好的依赖,传给 Options 的各回调。

func (Deps) IsMinimal

func (d Deps) IsMinimal() bool

IsMinimal 报告当前是否为显式最小模式。

type EventBus

type EventBus interface {
	outbox.Bus
	appkit.Subscriber
}

EventBus 同时是 relay 的投递出口(outbox.Bus)与消费者的订阅入口 (appkit.Subscriber)。DirectBus 是进程内实现;拆分部署换 NATS/Kafka 适配器,实现这两个接口即可,业务代码不变。

type Log

type Log struct {
	Level  string `koanf:"level" validate:"omitempty,oneof=debug info warn error"`
	Format string `koanf:"format" validate:"omitempty,oneof=json text"`
}

Log 是日志配置。

type Options

type Options struct {
	// Service 是服务名:遥测 service.name 与环境变量前缀的来源。必填。
	Service string
	// EnvPrefix 覆盖环境变量前缀,默认 strings.ToUpper(Service)。
	EnvPrefix string
	// DefaultAddr 覆盖默认监听地址,默认 ":8080"。
	DefaultAddr string
	// Modules 声明本进程可装配的模块全集(实际启用集由 -target 决定)。
	// 完整模式下 Deps.Pool 与 Deps.Bus 非 nil。必填。
	Modules func(Deps) ([]appkit.Module, error)
	// Minimal 声明显式 -minimal 模式装配的模块(通常挂个 ping 证明服务能起)。
	// 仅 env=dev 可启用;Deps.Pool 与 Deps.Bus 为 nil。提供此回调不会授权
	// database.url 缺失时自动降级,运行者仍必须显式传 -minimal。
	Minimal func(Deps) ([]appkit.Module, error)
	// AppOptions 追加 appkit.Option,典型用途是 appkit.Remote 绑定外域契约。
	AppOptions func(Deps) []appkit.Option
	// NewBus 覆盖默认事件总线(默认 outbox.NewDirectBus())。
	NewBus func() EventBus
	// AllowDirectBusForSplit 明确允许 target != all 时仍使用默认 DirectBus。
	// 这只适用于调用方确认事件不会跨进程的特殊部署;默认拒绝,避免生产者侧
	// 无本地订阅者却误把拆分部署当成可工作的跨进程事件总线。
	AllowDirectBusForSplit bool
	// PoolOptions 追加连接池配置,随 bootstrap 建的生产池生效:
	// pgtx.WithAfterConnect 装 per-connection 钩子(otelpgx tracer、
	// 会话级 GUC),pgtx.WithMaxConns 调容量。留空即框架默认。
	// 此前域要给池加钩子只能整个自建池绕开 bootstrap——迁移/outbox/
	// 幂等装配全部重写一遍,正是这条例外最不该存在的地方。
	PoolOptions []pgtx.PoolOption
	// AuthnPublicKey 是访问令牌的 Ed25519 验签公钥(组合根只持公钥,
	// 私钥在鉴权提供方)。security.mode=user_facing 时必填,并在根链
	// Base 之后挂 authn.Middleware:
	// 验签结果(appkit.Actor)注入 ctx,reg.Require / appkit.Check 据此
	// 判定。disabled 模式不得同时提供;内部服务身份由独立配置负责。
	AuthnPublicKey ed25519.PublicKey
	// AuthnIssuer 是期望的令牌 iss(提供方按分区签发,如 "rbac-demo")。
	// user_facing 模式必填,缺了启动报错——没有 iss 约束的验签
	// 会接受任何持私钥者签的令牌。
	AuthnIssuer string
}

Options 声明一个域服务的装配。除 Service 与 Modules 外均可留空。

type ProbeOptions added in v0.9.6

type ProbeOptions struct {
	Addr                     string
	NetworkBoundaryConfirmed bool
	Authenticate             func(http.Handler) http.Handler
}

ProbeOptions 配置独立的 Probe-only Listener。Addr 零值绑定到 loopback。 非 loopback 地址必须同时声明网络边界并提供认证中间件。

type ProfileDeps added in v0.9.6

type ProfileDeps struct {
	Log          *slog.Logger
	Base         Base
	Pool         *pgxpool.Pool
	Bus          EventBus
	Config       config.Options
	Capabilities Capabilities
}

ProfileDeps 是新 Profile 模块装配时可用的能力快照;与旧 Deps.IsMinimal 区分,避免把正式 no-database Profile 误判为 -minimal。

type ProfileOptions added in v0.9.6

type ProfileOptions struct {
	Service                string
	EnvPrefix              string
	DefaultAddr            string
	ConfigFile             string
	Target                 string
	Modules                func(ProfileDeps) ([]appkit.Module, error)
	AppOptions             func(ProfileDeps) []appkit.Option
	Security               SecurityOptions
	AuthnPublicKey         ed25519.PublicKey
	AuthnIssuer            string
	NewBus                 func() EventBus
	AllowDirectBusForSplit bool
	PoolOptions            []pgtx.PoolOption
	Capabilities           Capabilities
	Probe                  *ProbeOptions
}

ProfileOptions 配置新的可组合 Bootstrap Core。旧 Options、RunOptions 和 SecurityOptions 保持不变;旧完整 Profile 继续由 Main/RunWithSecurity 执行。

type RunOptions

type RunOptions struct {
	// Target 是本地实例化的模块集:"all" 或逗号分隔的模块名。
	Target string
	// ConfigFile 是配置文件路径,可缺省(此时只读环境变量)。
	ConfigFile string
	// MigrateOnly 为 true 时只应用迁移然后退出,不监听端口、不跑后台任务。
	MigrateOnly bool
	// Minimal 显式启用无数据库最小模式,仅允许 env=dev。
	Minimal bool
}

RunOptions 是运行期参数,对应 Main 解析出的命令行 flag。

type Runner added in v0.9.6

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

Runner 是新 Bootstrap Profile 的进程级入口,负责唯一一次注册并桥接 SIGINT/SIGTERM。Runner 与 Core 均为单次使用;嵌入式与 One-shot 调用不要使用它。

func NewRunner added in v0.9.6

func NewRunner(options ProfileOptions) *Runner

NewRunner 创建一个单次使用的进程级入口。进程级程序应由它调用 Core.Start, 不要再把其内部 Host 交给 App.Run 或安装第二个框架 Signal Handler。

func (*Runner) Run added in v0.9.6

func (r *Runner) Run(ctx context.Context) error

Run 注册一次 SIGINT/SIGTERM Handler 并桥接到 Host。Core 本身不接管进程信号。

type RunningProfile added in v0.9.6

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

RunningProfile 是 Bootstrap Core 启动的 Host。Wait 等待 Host 终态并关闭 Core 资源;Shutdown 受 Context 预算约束,预算耗尽时后台继续完成资源清理。

func (*RunningProfile) Readiness added in v0.9.6

func (r *RunningProfile) Readiness(ctx context.Context) (map[string]error, error)

Readiness 返回 Host 的程序化就绪检查结果,不要求开启 HTTP。

func (*RunningProfile) Shutdown added in v0.9.6

func (r *RunningProfile) Shutdown(ctx context.Context) error

Shutdown 请求 Host 关停;ctx 限制本次等待预算。若 Host 在预算耗尽后仍继续 清理,本方法及时返回,并在后台等 Host 终止后关闭连接池与 flush Telemetry; 后续 Wait 仍可读取最终运行/清理错误。

func (*RunningProfile) Wait added in v0.9.6

func (r *RunningProfile) Wait() error

Wait 等待 Host 终止并关闭 Core 资源。

type SecurityOptions added in v0.9.1

type SecurityOptions struct {
	ServiceVerifier *authn.ServiceVerifier
	// UserIssuers 用于单进程多用户签发方/分区,与 Options.AuthnPublicKey /
	// AuthnIssuer 互斥。密钥与 Partition 均来自可信组合根,不从请求选配置。
	UserIssuers map[string]authn.Issuer
}

SecurityOptions 是可选的服务身份及多用户签发方装配。独立于既有 Options/Base,避免给 已导出的结构体增加字段而破坏无键字面量调用方。

Jump to

Keyboard shortcuts

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