{"modulePath":"github.com/forgeplex/appkit","version":"v0.12.0","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package bootstrap\n\nPackage bootstrap 把域服务 main() 的固定装配收进框架。\n\n域服务的启动顺序是死的：加载配置 → 初始化遥测 → 建连接池 → 建事件总线 → 装配模块 → 运行 → 反序关停。这段仪式每个域仓库一字不差，却最容易被改坏， 且改坏了框架无从知情——少一个 tel.Shutdown 就丢 span，pool.Close 提前一步 就在关停期查询失败，忘了 Migrator 就静默不跑迁移。\n\n收进这里之后它位于 module cache（0444 只读），改不动也不必读。 用户仓库的 main 只声明\"装哪些模块\"，见 Options。\n\n## Functions\n\n```go\nfunc Main(o Options)\n```\nMain 是域服务 main() 的全部内容：解析 flag、装配、运行； 失败时打印到 stderr 并以退出码 1 结束。\n\n需要自定义 flag 或注入 ctx 时改用 Run。\n\n```go\nfunc MainWithSecurity(o Options, security SecurityOptions)\n```\nMainWithSecurity 与 Main 使用相同的运行参数，额外接收由组合根构造的 服务验签器或多用户签发方配置。私钥不属于接收端配置；security.mode 仍须显式声明。\n\n```go\nfunc Run(ctx context.Context, o Options, r RunOptions) error\n```\nRun 执行装配与运行，直到收到关停信号或运行期错误； r.MigrateOnly 为 true 时应用完迁移即返回。\n\n```go\nfunc RunWithSecurity(ctx context.Context, o Options, r RunOptions, security SecurityOptions) error\n```\nRunWithSecurity 在连接数据库、模块装配或监听端口前验证安全配置。 internal\\_service 要求有效 ServiceVerifier；user\\_facing 要求有效用户验签配置 （UserVerifier / security.oidc）；mixed 同时要求两者。 没有凭证的请求只可访问显式公开路由及探针。\n\n## Types\n\n```go\ntype Base struct {\n\tAddr     string   `koanf:\"addr\"`\n\tEnv      string   `koanf:\"env\" validate:\"omitempty,oneof=dev staging prod\"`\n\tDatabase Database `koanf:\"database\"`\n\tLog      Log      `koanf:\"log\"`\n\tDebug    Debug    `koanf:\"debug\"`\n}\n```\nBase 是每个域服务共有的配置项。需要额外配置项时，用 Deps.Config 再 config.Load 一次自己的结构——同一份文件与环境变量，不必重复声明这些。\n\n```go\ntype Capabilities struct {\n\tBusinessHTTP bool\n\tPostgreSQL   bool\n\tBus          bool\n\tMigrations   bool\n}\n```\nCapabilities 是新 Bootstrap Profile 可用的进程能力。HTTP 指业务入站 HTTP； Probe 是独立的只读健康/就绪 Listener。Migrations 必须依赖 PostgreSQL。\n\n```go\ntype Core struct {\n\t// contains filtered or unexported fields\n}\n```\nCore 持有单个 Profile 的配置、日志、Telemetry 与可选基础设施。 每个 Core 仅可启动一次；Start 用于嵌入式调用，Execute 执行一次性受管 函数。Core 不安装 OS Signal Handler。\n\n```go\nfunc NewCore(ctx context.Context, options ProfileOptions) (*Core, error)\n```\nNewCore 加载通用配置并初始化日志/Telemetry，再按显式 capability 打开可选 PostgreSQL 与 Bus。BusinessHTTP 关闭时不会加载或校验 HTTP SecurityMode。\n\n```go\nfunc (c *Core) Close(ctx context.Context) error\n```\nClose 关闭尚未启动的 Core；若 Host 已启动，则先请求优雅关停。Start 期间 不允许并发 Close，避免资源在装配中途被释放。\n\n```go\nfunc (c *Core) Execute(ctx context.Context, fn func(context.Context, ProfileDeps) error) error\n```\nExecute 以无监听、无 OS Signal 的 One-shot Profile 启动 App，执行 fn 后 优雅关停。fn 的错误与关停/Telemetry 错误通过 errors.Join 保留。\n\n```go\nfunc (c *Core) Start(ctx context.Context) (*RunningProfile, error)\n```\nStart 启动 Profile 并在 Host Ready 后返回；不注册 OS Signal Handler。\n\n```go\ntype Database struct {\n\t// URL 形如 postgres://user:pass@host:5432/db?sslmode=disable。\n\t// 留空时默认拒绝启动；本地零依赖试跑必须显式传 -minimal。\n\t// 生产部署必须配置。\n\tURL string `koanf:\"url\"`\n}\n```\nDatabase 是数据库配置。\n\n```go\ntype Debug struct {\n\t// Pprof 为 true 时挂 /debug/pprof/*（语义见 appkit.Pprof）。\n\tPprof bool `koanf:\"pprof\"`\n}\n```\nDebug 是排障端点配置。全部默认关闭：pprof 暴露进程内部信息 （goroutine 栈、堆采样可能含敏感数据），开启前先确认服务端口 不暴露公网或网络策略已挡好。 放配置而不是代码开关：线上排障改 configmap 重启即生效，不必发版。\n\n```go\ntype Deps struct {\n\t// Log 是已接入 trace 的服务日志器。\n\tLog *slog.Logger\n\t// Base 是已加载并填过默认值的框架配置。\n\tBase Base\n\t// Pool 是数据库连接池；最小模式下为 nil。\n\tPool *pgxpool.Pool\n\t// Bus 是事件总线；最小模式下为 nil。\n\tBus EventBus\n\t// Config 复现框架加载配置时的入参。需要额外配置项时：\n\t//   cfg, err := config.Load[myConfig](d.Config)\n\tConfig config.Options\n}\n```\nDeps 是框架已备好的依赖，传给 Options 的各回调。\n\n```go\nfunc (d Deps) IsMinimal() bool\n```\nIsMinimal 报告当前是否为显式最小模式。\n\n```go\ntype EventBus interface {\n\toutbox.Bus\n\tappkit.Subscriber\n}\n```\nEventBus 同时是 relay 的投递出口（outbox.Bus）与消费者的订阅入口 （appkit.Subscriber）。DirectBus 是进程内实现；拆分部署换 NATS/Kafka 适配器，实现这两个接口即可，业务代码不变。\n\n```go\ntype Log struct {\n\tLevel  string `koanf:\"level\" validate:\"omitempty,oneof=debug info warn error\"`\n\tFormat string `koanf:\"format\" validate:\"omitempty,oneof=json text\"`\n}\n```\nLog 是日志配置。\n\n```go\ntype Options struct {\n\t// Service 是服务名：遥测 service.name 与环境变量前缀的来源。必填。\n\tService string\n\t// EnvPrefix 覆盖环境变量前缀，默认 strings.ToUpper(Service)。\n\tEnvPrefix string\n\t// DefaultAddr 覆盖默认监听地址，默认 \":8080\"。\n\tDefaultAddr string\n\t// Modules 声明本进程可装配的模块全集（实际启用集由 -target 决定）。\n\t// 完整模式下 Deps.Pool 与 Deps.Bus 非 nil。必填。\n\tModules func(Deps) ([]appkit.Module, error)\n\t// Minimal 声明显式 -minimal 模式装配的模块（通常挂个 ping 证明服务能起）。\n\t// 仅 env=dev 可启用；Deps.Pool 与 Deps.Bus 为 nil。提供此回调不会授权\n\t// database.url 缺失时自动降级，运行者仍必须显式传 -minimal。\n\tMinimal func(Deps) ([]appkit.Module, error)\n\t// AppOptions 追加 appkit.Option，典型用途是 appkit.Remote 绑定外域契约。\n\tAppOptions func(Deps) []appkit.Option\n\t// NewBus 覆盖默认事件总线（默认 outbox.NewDirectBus()）。\n\tNewBus func() EventBus\n\t// AllowDirectBusForSplit 明确允许 target != all 时仍使用默认 DirectBus。\n\t// 这只适用于调用方确认事件不会跨进程的特殊部署；默认拒绝，避免生产者侧\n\t// 无本地订阅者却误把拆分部署当成可工作的跨进程事件总线。\n\tAllowDirectBusForSplit bool\n\t// PoolOptions 追加连接池配置，随 bootstrap 建的生产池生效：\n\t// pgtx.WithAfterConnect 装 per-connection 钩子（otelpgx tracer、\n\t// 会话级 GUC），pgtx.WithMaxConns 调容量。留空即框架默认。\n\t// 此前域要给池加钩子只能整个自建池绕开 bootstrap——迁移/outbox/\n\t// 幂等装配全部重写一遍，正是这条例外最不该存在的地方。\n\tPoolOptions []pgtx.PoolOption\n}\n```\nOptions 声明一个域服务的装配。除 Service 与 Modules 外均可留空。\n\n```go\ntype ProbeOptions struct {\n\tAddr                     string\n\tNetworkBoundaryConfirmed bool\n\tAuthenticate             func(http.Handler) http.Handler\n}\n```\nProbeOptions 配置独立的 Probe-only Listener。Addr 零值绑定到 loopback。 非 loopback 地址必须同时声明网络边界并提供认证中间件。\n\n```go\ntype ProfileDeps struct {\n\tLog          *slog.Logger\n\tBase         Base\n\tPool         *pgxpool.Pool\n\tBus          EventBus\n\tConfig       config.Options\n\tCapabilities Capabilities\n}\n```\nProfileDeps 是新 Profile 模块装配时可用的能力快照；与旧 Deps.IsMinimal 区分，避免把正式 no-database Profile 误判为 -minimal。\n\n```go\ntype ProfileOptions struct {\n\tService                string\n\tEnvPrefix              string\n\tDefaultAddr            string\n\tConfigFile             string\n\tTarget                 string\n\tModules                func(ProfileDeps) ([]appkit.Module, error)\n\tAppOptions             func(ProfileDeps) []appkit.Option\n\tSecurity               SecurityOptions\n\tNewBus                 func() EventBus\n\tAllowDirectBusForSplit bool\n\tPoolOptions            []pgtx.PoolOption\n\tCapabilities           Capabilities\n\tProbe                  *ProbeOptions\n}\n```\nProfileOptions 配置新的可组合 Bootstrap Core。旧 Options、RunOptions 和 SecurityOptions 保持不变；旧完整 Profile 继续由 Main/RunWithSecurity 执行。\n\n```go\ntype RunOptions struct {\n\t// Target 是本地实例化的模块集：\"all\" 或逗号分隔的模块名。\n\tTarget string\n\t// ConfigFile 是配置文件路径，可缺省（此时只读环境变量）。\n\tConfigFile string\n\t// MigrateOnly 为 true 时只应用迁移然后退出，不监听端口、不跑后台任务。\n\tMigrateOnly bool\n\t// Minimal 显式启用无数据库最小模式，仅允许 env=dev。\n\tMinimal bool\n}\n```\nRunOptions 是运行期参数，对应 Main 解析出的命令行 flag。\n\n```go\ntype Runner struct {\n\t// contains filtered or unexported fields\n}\n```\nRunner 是新 Bootstrap Profile 的进程级入口，负责唯一一次注册并桥接 SIGINT/SIGTERM。Runner 与 Core 均为单次使用；嵌入式与 One-shot 调用不要使用它。\n\n```go\nfunc NewRunner(options ProfileOptions) *Runner\n```\nNewRunner 创建一个单次使用的进程级入口。进程级程序应由它调用 Core.Start， 不要再把其内部 Host 交给 App.Run 或安装第二个框架 Signal Handler。\n\n```go\nfunc (r *Runner) Run(ctx context.Context) error\n```\nRun 注册一次 SIGINT/SIGTERM Handler 并桥接到 Host。Core 本身不接管进程信号。\n\n```go\ntype RunningProfile struct {\n\t// contains filtered or unexported fields\n}\n```\nRunningProfile 是 Bootstrap Core 启动的 Host。Wait 等待 Host 终态并关闭 Core 资源；Shutdown 受 Context 预算约束，预算耗尽时后台继续完成资源清理。\n\n```go\nfunc (r *RunningProfile) Readiness(ctx context.Context) (map[string]error, error)\n```\nReadiness 返回 Host 的程序化就绪检查结果，不要求开启 HTTP。\n\n```go\nfunc (r *RunningProfile) Shutdown(ctx context.Context) error\n```\nShutdown 请求 Host 关停；ctx 限制本次等待预算。若 Host 在预算耗尽后仍继续 清理，本方法及时返回，并在后台等 Host 终止后关闭连接池与 flush Telemetry； 后续 Wait 仍可读取最终运行/清理错误。\n\n```go\nfunc (r *RunningProfile) Wait() error\n```\nWait 等待 Host 终止并关闭 Core 资源。\n\n```go\ntype SecurityOptions struct {\n\tServiceVerifier *authn.ServiceVerifier\n\t// UserVerifier 用于校验来自 forgeplex/sso 等多 Realm OIDC 提供方的用户访问令牌，\n\t// 与声明式 security.oidc 互斥。\n\tUserVerifier *authn.OIDCVerifier\n}\n```\nSecurityOptions 是可选的服务身份与用户验签器装配。独立于既有 Options/Base，避免给 已导出的结构体增加字段而破坏无键字面量调用方。\n\n","path":"github.com/forgeplex/appkit/bootstrap","name":"bootstrap","synopsis":"Package bootstrap 把域服务 main() 的固定装配收进框架。","isRedistributable":true}
