增加安全字段校验提示、请求预算和就绪/存活探针, 让绑定、数据库、Redis 和出站响应解码保留可信诊断上下文。 补充完整应用装配及逆序清理示例,同步接入和迁移文档。 验证:make verify、make race-check 全部通过。 BREAKING CHANGE: 普通 Controller 默认启用 30 秒协作式请求预算, 可用 request_timeout_ms: 0 或 max-exec-time:"0" 关闭; 字段校验失败的 400 响应增加安全字段明细。
This commit is contained in:
1 parent
b4c3ac622c
commit
3196e45a01
22 files changed
+1294
-79
No files matched your search
@@ -0,0 +1,21 @@
|
||||
address: 127.0.0.1:8080
|
||||
log_directory: ./logs/application
|
||||
http:
|
||||
service: application-example
|
||||
request_timeout_ms: 30000
|
||||
outbound:
|
||||
timeout_ms: 30000
|
||||
connect_timeout_ms: 5000
|
||||
max_response_bytes: 8388608
|
||||
# 可选依赖:配置后必须初始化成功;凭据由部署环境注入。
|
||||
# database:
|
||||
# name: primary
|
||||
# host: 127.0.0.1
|
||||
# port: 3306
|
||||
# username: ${DATABASE_USERNAME}
|
||||
# password: ${DATABASE_PASSWORD}
|
||||
# database: ${DATABASE_NAME}
|
||||
# redis:
|
||||
# name: cache
|
||||
# address: 127.0.0.1:6379
|
||||
# password: ${REDIS_PASSWORD}
|
||||
@@ -0,0 +1,188 @@
|
||||
// Command application 展示配置、日志、连接、出站客户端、健康检查和退出的完整装配。
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.zhangdeman.cn/github/ginframework/config"
|
||||
"git.zhangdeman.cn/github/ginframework/database"
|
||||
"git.zhangdeman.cn/github/ginframework/fault"
|
||||
framework "git.zhangdeman.cn/github/ginframework/http"
|
||||
"git.zhangdeman.cn/github/ginframework/httpclient"
|
||||
"git.zhangdeman.cn/github/ginframework/logger"
|
||||
cache "git.zhangdeman.cn/github/ginframework/redis"
|
||||
"github.com/gin-gonic/gin"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const (
|
||||
codeAddress = 990101
|
||||
codeListen = 990102
|
||||
codeRedisClose = 990103
|
||||
)
|
||||
|
||||
type applicationConfig struct {
|
||||
Address string `json:"address" yaml:"address" dc:"服务监听地址,包含端口"`
|
||||
LogDirectory string `json:"log_directory" yaml:"log_directory" dc:"本应用拥有的日志目录"`
|
||||
HTTP framework.Config `json:"http" yaml:"http" dc:"HTTP 数据配置"`
|
||||
Database *database.Config `json:"database,omitempty" yaml:"database" dc:"可选数据库,配置后必须初始化成功"`
|
||||
Redis *cache.Config `json:"redis,omitempty" yaml:"redis" dc:"可选 Redis,配置后必须初始化成功"`
|
||||
Outbound httpclient.Config `json:"outbound" yaml:"outbound" dc:"应用复用的出站客户端策略"`
|
||||
}
|
||||
|
||||
type resources struct {
|
||||
database *database.Connection `dc:"尚未对业务发布的数据库连接"`
|
||||
redis *redisclient.Client `dc:"尚未对业务发布的 Redis 客户端"`
|
||||
outbound *httpclient.Client `dc:"应用复用并拥有空闲连接池的出站客户端"`
|
||||
}
|
||||
|
||||
type pingForm struct {
|
||||
framework.Meta `path:"/ping" method:"GET" summary:"完整装配示例" tag:"example" dc:"路由声明"`
|
||||
}
|
||||
|
||||
type pingOutput struct {
|
||||
Status string `json:"status" dc:"示例处理结果"`
|
||||
}
|
||||
|
||||
type example struct{}
|
||||
|
||||
// Ping 返回普通请求结果,基础依赖已经由应用装配完成。
|
||||
// 入参:ctx 为已建立预算的请求,input 为完成校验的 Form。
|
||||
// 返回:公开结果,无业务错误时返回 nil。
|
||||
func (*example) Ping(ctx *gin.Context, input *pingForm) (*pingOutput, error) {
|
||||
return &pingOutput{Status: "ok"}, nil
|
||||
}
|
||||
|
||||
// main 加载显式配置并把进程信号转换为取消上下文。
|
||||
func main() {
|
||||
path := flag.String("config", "examples/application/config.yml", "应用配置路径")
|
||||
flag.Parse()
|
||||
var (
|
||||
cfg applicationConfig
|
||||
)
|
||||
if err := config.Load(*path, &cfg, config.Options{}); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
if err := run(ctx, cfg); err != nil {
|
||||
// 装配和清理错误均在本示例或组件源头记录,入口只设置退出状态。
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// run 只在本函数中创建和连接依赖,失败逆序回收,退出先排空请求。
|
||||
// 入参:ctx 为进程取消上下文,cfg 为完成 YAML 解析的应用配置。
|
||||
// 返回:装配、监听、排空或资源回收失败时保留完整错误链。
|
||||
func run(ctx context.Context, cfg applicationConfig) (err error) {
|
||||
if _, _, err = net.SplitHostPort(cfg.Address); err != nil {
|
||||
classified := fault.New(codeAddress, "validate application listen address failed", err)
|
||||
logger.RecordErrorContext(ctx, "validate application listen address failed", classified)
|
||||
return classified
|
||||
}
|
||||
instance, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: cfg.LogDirectory, UseJSON: true, LogLevel: "info"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pending := &resources{}
|
||||
// 释放时仍有可用日志;已成功返回的资源由当前装配根负责。
|
||||
defer func() { err = errors.Join(err, pending.close(), logger.CloseOutputs()) }()
|
||||
if cfg.Database != nil {
|
||||
if pending.database, err = database.Open(ctx, *cfg.Database, database.Options{Logger: instance}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if cfg.Redis != nil {
|
||||
if pending.redis, err = cache.Open(ctx, *cfg.Redis, instance); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if pending.outbound, err = httpclient.New(cfg.Outbound, httpclient.Options{Logger: instance}); err != nil {
|
||||
return err
|
||||
}
|
||||
server, err := framework.NewServer(cfg.HTTP, framework.Options{AccessLogger: instance})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 无论注册、监听还是 Serve 提前失败,返回前均完成请求排空。
|
||||
defer func() { server.SetReady(false); err = errors.Join(err, server.Shutdown(context.Background())) }()
|
||||
if err = server.RegisterHealth("/_health", framework.HealthOptions{Checks: pending.checks()}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = server.Group("/example", nil, &example{}); err != nil {
|
||||
return err
|
||||
}
|
||||
listener, err := net.Listen("tcp", cfg.Address)
|
||||
if err != nil {
|
||||
classified := fault.New(codeListen, "listen application example failed", err)
|
||||
logger.RecordErrorContext(ctx, "listen application example failed", classified)
|
||||
return classified
|
||||
}
|
||||
defer listener.Close()
|
||||
// 到这里全部配置的依赖已成功,才发布可被就绪探针观察到的服务。
|
||||
server.SetReady(true)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- server.Serve(listener) }()
|
||||
select {
|
||||
case err = <-done:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
server.SetReady(false)
|
||||
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
return errors.Join(server.Shutdown(shutdown), <-done)
|
||||
}
|
||||
}
|
||||
|
||||
// checks 构建固定的依赖探测列表,不创建第二套连接。
|
||||
// 返回:只引用本装配根实际启用资源的检查函数。
|
||||
func (r *resources) checks() []framework.ReadinessCheck {
|
||||
var (
|
||||
checks []framework.ReadinessCheck
|
||||
)
|
||||
if r.database != nil {
|
||||
checks = append(checks, framework.ReadinessCheck{Name: "database", Check: func(ctx context.Context) error {
|
||||
pool, err := r.database.Session(ctx).DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return pool.PingContext(ctx)
|
||||
}})
|
||||
}
|
||||
if r.redis != nil {
|
||||
checks = append(checks, framework.ReadinessCheck{Name: "redis", Check: func(ctx context.Context) error { return r.redis.Ping(ctx).Err() }})
|
||||
}
|
||||
return checks
|
||||
}
|
||||
|
||||
// close 逆序释放本次装配创建的资源,不包含仍在途的业务处理。
|
||||
// 返回:全部关闭结果合并的原因链,每个对象均会尝试回收。
|
||||
func (r *resources) close() error {
|
||||
var (
|
||||
result []error
|
||||
)
|
||||
if r.outbound != nil {
|
||||
r.outbound.CloseIdleConnections()
|
||||
r.outbound = nil
|
||||
}
|
||||
if r.redis != nil {
|
||||
if err := r.redis.Close(); err != nil {
|
||||
classified := fault.New(codeRedisClose, "close application Redis failed", err)
|
||||
logger.RecordError("close application Redis failed", classified)
|
||||
result = append(result, classified)
|
||||
}
|
||||
r.redis = nil
|
||||
}
|
||||
if r.database != nil {
|
||||
result = append(result, r.database.Close())
|
||||
r.database = nil
|
||||
}
|
||||
return errors.Join(result...)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zhangdeman.cn/github/ginframework/database"
|
||||
"git.zhangdeman.cn/github/ginframework/httpclient"
|
||||
"git.zhangdeman.cn/github/ginframework/logger"
|
||||
cache "git.zhangdeman.cn/github/ginframework/redis"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
"gorm.io/driver/sqlite"
|
||||
)
|
||||
|
||||
func TestConfiguredDependencyFailureReleasesLogging(t *testing.T) {
|
||||
cfg := applicationConfig{Address: "127.0.0.1:0", LogDirectory: t.TempDir(), Redis: &cache.Config{}}
|
||||
if err := run(context.Background(), cfg); err == nil {
|
||||
t.Fatal("configured Redis failure was silently ignored")
|
||||
}
|
||||
if _, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: t.TempDir()}); err != nil {
|
||||
t.Fatal("startup failure leaked global logs", err)
|
||||
}
|
||||
if err := logger.CloseOutputs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPartialResourceCleanupClosesNativePools(t *testing.T) {
|
||||
connection, err := database.Open(context.Background(), database.Config{}, database.Options{Dialector: sqlite.Open(":memory:")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool, err := connection.Session(context.Background()).DB()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
redis := redisclient.NewClient(&redisclient.Options{Network: "unix", Addr: filepath.Join(t.TempDir(), "unused.sock")})
|
||||
outbound, err := httpclient.New(httpclient.Config{}, httpclient.Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending := &resources{database: connection, redis: redis, outbound: outbound}
|
||||
if err = pending.close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pool.PingContext(context.Background()) == nil || redis.Ping(context.Background()).Err() == nil {
|
||||
t.Fatal("partial resources remained open")
|
||||
}
|
||||
if pending.database != nil || pending.redis != nil || pending.outbound != nil {
|
||||
t.Fatal("closed handles still published")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationReadinessAndSignalStyleShutdown(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address := listener.Addr().String()
|
||||
listener.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
result := make(chan error, 1)
|
||||
go func() { result <- run(ctx, applicationConfig{Address: address, LogDirectory: t.TempDir()}) }()
|
||||
client := &http.Client{Timeout: 200 * time.Millisecond}
|
||||
ready := false
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
response, err := client.Get("http://" + address + "/_health/ready")
|
||||
if err == nil {
|
||||
response.Body.Close()
|
||||
if response.StatusCode == 200 {
|
||||
ready = true
|
||||
break
|
||||
}
|
||||
}
|
||||
select {
|
||||
case err := <-result:
|
||||
t.Fatalf("application exited before ready: %v", err)
|
||||
default:
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if !ready {
|
||||
cancel()
|
||||
<-result
|
||||
t.Fatal("application never became ready")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err = <-result:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("application failed to drain")
|
||||
}
|
||||
if _, err = logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: t.TempDir()}); err != nil {
|
||||
t.Fatal("shutdown leaked logs", err)
|
||||
}
|
||||
if err = logger.CloseOutputs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||