From 3196e45a0128b106e338069def4719adec66b184 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 26 Nov 2026 20:41:33 -0800 Subject: [PATCH] =?UTF-8?q?feat(http)!:=20=E8=A1=A5=E9=BD=90=E6=A0=B8?= =?UTF-8?q?=E5=BF=83=E8=AF=B7=E6=B1=82=E5=A4=84=E7=90=86=E4=B8=8E=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F=E8=83=BD=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加安全字段校验提示、请求预算和就绪/存活探针, 让绑定、数据库、Redis 和出站响应解码保留可信诊断上下文。 补充完整应用装配及逆序清理示例,同步接入和迁移文档。 验证:make verify、make race-check 全部通过。 BREAKING CHANGE: 普通 Controller 默认启用 30 秒协作式请求预算, 可用 request_timeout_ms: 0 或 max-exec-time:"0" 关闭; 字段校验失败的 400 响应增加安全字段明细。 --- README.md | 8 + database/connection.go | 20 +- docs/getting-started.md | 58 ++++- docs/integration-optimization-review.md | 2 + docs/migration.md | 9 +- examples/application/config.yml | 21 ++ examples/application/main.go | 188 ++++++++++++++++ examples/application/main_test.go | 108 +++++++++ http/budget.go | 33 +++ http/context_flow_test.go | 161 ++++++++++++++ http/health.go | 103 +++++++++ http/p1_test.go | 277 ++++++++++++++++++++++++ http/request/body.go | 10 +- http/request/context.go | 22 ++ http/request/form.go | 92 ++++---- http/request/validation.go | 164 ++++++++++++++ http/response.go | 13 ++ http/routes.go | 43 +++- http/server.go | 12 + httpclient/request.go | 17 +- internal/failure/error.go | 8 + redis/client.go | 4 +- 22 files changed, 1294 insertions(+), 79 deletions(-) create mode 100644 examples/application/config.yml create mode 100644 examples/application/main.go create mode 100644 examples/application/main_test.go create mode 100644 http/budget.go create mode 100644 http/context_flow_test.go create mode 100644 http/health.go create mode 100644 http/p1_test.go create mode 100644 http/request/context.go create mode 100644 http/request/validation.go diff --git a/README.md b/README.md index 43e90e6..613433b 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,14 @@ go run ./examples/minimal 请求 `http://127.0.0.1:8080/example/ping?name=world`。不需要启动 MySQL 或 Redis。消费项目的分支版本会被 Go 解析为固定伪版本,后续升级选择已审核提交或已发布 tag。 +完整资源装配、健康检查和退出示例: + +```sh +go run ./examples/application -config examples/application/config.yml +``` + +普通 Controller 默认有 30 秒合作式预算;校验错误提供安全字段提示。健康检查需由应用显式注册并在依赖就绪后置为 ready,详见接入指南。 + ## 开发与验证 先读取 [AGENTS.md](AGENTS.md) 和 [工程技术规约](docs/standards/technical-specification.md)。 diff --git a/database/connection.go b/database/connection.go index 915269f..48d96f0 100644 --- a/database/connection.go +++ b/database/connection.go @@ -79,12 +79,12 @@ func Open(ctx context.Context, cfg Config, options Options) (result *Connection, maxIdle = *cfg.MaxIdle } if cfg.ProbeTimeoutMS < 0 || maxOpen < 0 || maxIdle < 0 || cfg.Port < 0 || cfg.Port > 65535 || (maxOpen > 0 && maxIdle > maxOpen) { - return nil, fault.Wrap(CodeConfig, "validate database configuration failed", errors.New("invalid pool, port or probe setting")) + return nil, fault.WrapContext(ctx, CodeConfig, "validate database configuration failed", errors.New("invalid pool, port or probe setting")) } dialect := options.Dialector if dialect == nil { if cfg.Host == "" || cfg.Database == "" { - return nil, fault.Wrap(CodeTarget, "validate MySQL target failed", errors.New("MySQL host and database are required")) + return nil, fault.WrapContext(ctx, CodeTarget, "validate MySQL target failed", errors.New("MySQL host and database are required")) } if cfg.Port == 0 { cfg.Port = 3306 @@ -97,7 +97,7 @@ func Open(ctx context.Context, cfg Config, options Options) (result *Connection, } location, locationErr := time.LoadLocation(cfg.Timezone) if locationErr != nil { - return nil, fault.Wrap(CodeTimezone, "resolve MySQL timezone failed", locationErr) + return nil, fault.WrapContext(ctx, CodeTimezone, "resolve MySQL timezone failed", locationErr) } driver := mysqlDriver.NewConfig() driver.User, driver.Passwd, driver.Net, driver.Addr, driver.DBName = cfg.Username, cfg.Password, "tcp", net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)), cfg.Database @@ -110,18 +110,18 @@ func Open(ctx context.Context, cfg Config, options Options) (result *Connection, if openErr != nil { if orm != nil { if pool, poolErr := orm.DB(); poolErr == nil { - openErr = errors.Join(openErr, fault.Wrap(CodeClose, "close failed database pool failed", pool.Close())) + openErr = errors.Join(openErr, fault.WrapContext(ctx, CodeClose, "close failed database pool failed", pool.Close())) } } - return nil, fault.Wrap(CodeOpen, "open database failed", openErr) + return nil, fault.WrapContext(ctx, CodeOpen, "open database failed", openErr) } pool, poolErr := orm.DB() if poolErr != nil { - return nil, fault.Wrap(CodePool, "resolve database pool failed", poolErr) + return nil, fault.WrapContext(ctx, CodePool, "resolve database pool failed", poolErr) } defer func() { if err != nil { - err = errors.Join(err, fault.Wrap(CodeClose, "close pending database pool failed", pool.Close())) + err = errors.Join(err, fault.WrapContext(ctx, CodeClose, "close pending database pool failed", pool.Close())) } }() pool.SetMaxOpenConns(maxOpen) @@ -132,14 +132,14 @@ func Open(ctx context.Context, cfg Config, options Options) (result *Connection, probe, cancel := context.WithTimeout(ctx, time.Duration(cfg.ProbeTimeoutMS)*time.Millisecond) defer cancel() if err = pool.PingContext(probe); err != nil { - return nil, fault.Wrap(CodeProbe, "probe database failed", err) + return nil, fault.WrapContext(ctx, CodeProbe, "probe database failed", err) } for _, plugin := range options.Plugins { if plugin == nil { - return nil, fault.Wrap(CodePlugin, "install database plugin failed", errors.New("database plugin is nil")) + return nil, fault.WrapContext(ctx, CodePlugin, "install database plugin failed", errors.New("database plugin is nil")) } if err = orm.Use(plugin); err != nil { - return nil, fault.Wrap(CodePlugin, "install database plugin failed", err) + return nil, fault.WrapContext(ctx, CodePlugin, "install database plugin failed", err) } } return &Connection{root: orm, pool: pool}, nil diff --git a/docs/getting-started.md b/docs/getting-started.md index 97601ae..9ded748 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -35,8 +35,8 @@ go mod tidy | `database/sqllog` | GORM 官方 Trace 与 SQL 脱敏 | 自建原生 GORM 的可选日志适配 | | `redis` | 原生 Redis 客户端创建与探测 | 应用装配根 | | `redis/commandlog` | 官方 Hook 与 Pipeline 执行观测 | 自建原生 Redis 的可选日志适配 | -| `http` | Gin Server、Form/Meta、响应、可信注入、原生路由、流式截止与排空 | HTTP 入口 | -| `http/request` | URI/Query/Body、multipart、正文限制与 validator 规则 | 自定义请求适配 | +| `http` | Gin Server、Form/Meta、响应、可信注入、健康检查、合作式预算与排空 | HTTP 入口 | +| `http/request` | URI/Query/Body、multipart、正文限制、Context 校验与字段级提示 | 自定义请求适配 | | `httpclient` | 出站连接池、请求编码、有界响应、原生流式与安全流水 | 第三方服务适配 | @@ -87,7 +87,7 @@ if err = server.Group("/api", nil, &Example{}); err != nil { } ``` -完整路由为 `GET /api/ping`。Form 的 path 不重复声明入口前缀。支持的 tag 是 `path`、`method`、`summary`、`tag`、`max-body-bytes`;method 可用逗号声明多个方法。Controller 使用指针实例,方法签名为 `func(*gin.Context, Form或*Form) (公开结果, error)`。 +完整路由为 `GET /api/ping`。Form 的 path 不重复声明入口前缀。支持的 tag 是 `path`、`method`、`summary`、`tag`、`max-body-bytes`、`max-exec-time`;method 可用逗号声明多个方法。Controller 使用指针实例,方法签名为 `func(*gin.Context, Form或*Form) (公开结果, error)`。 同一 Group 可一次传多个 Controller;整批检查成功后才提交。`Handler()`、`Serve(listener)` 或 `Shutdown(ctx)` 会冻结后续注册。不能在服务运行中继续添加路由。`Routes()` 返回包含最终完整路径的副本,可交给应用文档生成器。 @@ -101,11 +101,19 @@ if err = server.Group("/api", nil, &Example{}); err != nil { 顺序固定为 URI → Query → Body → 默认值 → 可信字段 → 一次最终校验。GET/HEAD/OPTIONS 不使用 Body 覆盖参数;POST/PUT/PATCH/DELETE 支持 JSON、URL 编码表单及 multipart。JSON 支持 `+json` 类型,拒绝多份根 JSON。 -默认请求正文上限 4 MiB,单路由可通过 `max-body-bytes:"8388608"` 调整,单位字节。正文超限返回 413,不支持的媒体类型返回 415,一般绑定/校验失败返回安全 400。上传文件字段可用 multipart.FileHeader、*multipart.FileHeader 或 []*multipart.FileHeader。 +默认请求正文上限 4 MiB,单路由可通过 `max-body-bytes:"8388608"` 调整,单位字节。正文超限返回 413,不支持的媒体类型返回 415,一般绑定失败返回安全 400;字段约束失败返回 400,data.fields 包含安全的字段名、规则和提示。上传文件字段可用 multipart.FileHeader、*multipart.FileHeader 或 []*multipart.FileHeader。 Form 的 default tag 延续 go-defaults 行为,标量零值可能被认为缺省;需区分“未传”和“显式零值”时使用指针并补对应测试。没有 JSON 全字段存在性跟踪。 -自定义原生 Gin Handler 可使用 `request.Form.Parse(ctx, &form)` 一次完成绑定、默认值和校验;若要在中间注入可信字段,顺序是 `Bind → defaults.SetDefaults(&form) → 应用显式注入可信字段 → Validate`,不能再重复 Parse。这里 defaults 是 github.com/mcuadros/go-defaults;Bind 和 Validate 本身不会设置默认值。自定义字段规则通过 `request.RegisterValidation` 在启动期登记,规则函数使用 validator/v10 原生类型。 +自定义原生 Gin Handler 可使用 `request.Form.Parse(ctx, &form)` 一次完成绑定、默认值和校验;若要在中间注入可信字段,顺序是 `Bind → defaults.SetDefaults(&form) → 应用显式注入可信字段 → ValidateContext(ctx.Request.Context(), &form)`,不能再重复 Parse。这里 defaults 是 github.com/mcuadros/go-defaults;Bind 和 ValidateContext 本身不会设置默认值。Validate(receiver) 保留为无请求来源的兼容入口;HTTP/Worker 的显式校验优先使用 ValidateContext,保留标准上下文诊断。自定义字段规则通过 `request.RegisterValidation` 在启动期登记,规则函数使用 validator/v10 原生类型。 + +字段提示使用 json/form/uri 中声明的公开名称,嵌入 Input 不增加对象层级,集合位置统一为 [],例如 profile.email、items[].email。返回 rule 但不返回校验参数、原始输入、Map 键和内部 Form 类型名;常见规则有默认英文提示,可用字段静态 err 标签提供安全文案。未知映射使用 request。调用方可通过 errors.As 继续识别 request.ValidationError 和底层 validator.ValidationErrors。 + +校验错误示例: + +```json +{"code":400,"message":"Validation failed","data":{"fields":[{"field":"email","rule":"email","message":"Invalid email address"}]},"trace_id":"trusted-request-id","cost_ms":1} +``` ### 4.2 可信身份 @@ -150,7 +158,31 @@ err := server.Handle(http.MethodGet, "/events", 这里 http 是标准库 net/http,framework 是框架 http 包。Deadline 只派生上下文,不缓冲或替换 Writer;业务须监听取消并停止写出。生产事件内容、连接确认、结束事件及业务 Hook 由应用定义。 -旧 `is-sse`、`is-ws`、`max-exec-time`、`rate-limit`、`no-login`、`hook-sync`、`output_strict` tag 当前明确拒绝。WebSocket 没有内置实现。不要把旧 Form 原样搬入后假定安全策略会自动生效。 +旧 `is-sse`、`is-ws`、`rate-limit`、`no-login`、`hook-sync`、`output_strict` tag 当前明确拒绝。WebSocket 没有内置实现。不要把旧 Form 原样搬入后假定安全策略会自动生效。 + +### 5.1 普通 Controller 请求预算 + +Config.RequestTimeoutMS 是 *int64,缺省 30000 毫秒,显式零禁用。Form 的 max-exec-time tag 按秒覆盖本路由,0 禁用;负值和时长溢出在注册期拒绝。构造时复制配置,不受调用方后续修改指针影响。 + +预算从 Controller 适配函数开始,覆盖参数绑定、可信注入、校验和业务调用;此前的全局/组中间件如需预算,由应用显式传递 Context。预算会派生到数据库会话、Redis 命令及出站请求。截止后处理函数合作退出,框架返回安全的 504;客户端取消不继续写响应。 + +这是合作式预算,不是强杀或后台脱离执行:处理函数、依赖和原始正文读取必须遵守取消;忽略 Context 的函数或阻塞 Reader 可能延长请求。框架在它们结束前不会释放其依赖,也不会跨协程复用 Gin Writer。已写出的响应不再覆盖。不能把它当作网络层慢上传硬截止,监听器/反向代理的网络超时由部署显式配置。 + +原生 Handle 路由不自动套用普通 Controller 预算,SSE 使用 Deadline 和请求取消;标准超时响应不替换流式 Writer。 + +### 5.2 存活与就绪检查 + +启动期调用 server.RegisterHealth("/_health", framework.HealthOptions{...}),一次注册 GET /_health/live 和 GET /_health/ready。两条路由也受冲突检查和注册冻结约束。 + +- live 仅表示当前进程能够处理请求,不主动探测数据库或 Redis;正常返回 200。 +- ready 初始返回 503。应用完成全部依赖创建、业务装配及路由注册后调用 SetReady(true),探测全部成功才返回 200。 +- HealthOptions.Checks 是启动期固定的 ReadinessCheck 列表,每项包含安全 Name 和 Check func(context.Context) error。复用已创建的池,不新建连接;失败只公开名称和 ready=false,不输出地址、密码或原始错误。 +- TimeoutMS 是本次就绪探测的合作式总预算,缺省 1000 毫秒,回调必须响应 Context;没有后台探测 goroutine 或动态注册中心。 +- 部署开始摘流时调用 SetReady(false);Shutdown 自动置 false,随后停止接收和排空请求。 + +健康路由仍经过应用配置的全局中间件。认证中间件应显式按部署策略允许探针,或将其放在受控内网入口,框架不自动绕过认证。 + +完整示例以 pool.PingContext 和 redisClient.Ping(ctx) 构建检查,业务实现可以添加自己的真实依赖探测。 ## 6. 配置、日志与诊断 @@ -196,7 +228,7 @@ Name 和 Path 必填;MaxAge 单位秒,非正值使用三天。文件轮转 ### 6.3 Context 与内部错误 -后台入口用 `diagnostic.With(ctx, diagnostic.Snapshot{...})` 建立可信标量快照;无请求来源时不要伪造 request_id。`diagnostic.From(ctx)` 返回副本。普通业务能力使用标准 context.Context,避免为了日志构造伪 Gin 请求。 +后台入口用 `diagnostic.With(ctx, diagnostic.Snapshot{...})` 建立可信标量快照;无请求来源时不要伪造 request_id。`diagnostic.From(ctx)` 返回副本。普通业务能力使用标准 context.Context,避免为了日志构造伪 Gin 请求。请求绑定、校验、可信注入、连接启动错误和出站错误均在接收处使用该上下文记录;出站 Response 只保存可信标量诊断副本,让后续 DecodeJSON 的错误仍可关联原请求,不持有 HTTP 请求或可变 Context。 `fault.New(code, summary, cause)` 只创建内部错误,支持 errors.Is/As 和 Unwrap,不自动写日志。应用主动创建此类错误时需在源头调用 `logger.RecordErrorContext(ctx, 英文摘要, err)` 一次,上层只传播。源头错误码使用稳定具名常量;不得作为公开 HTTP 业务码输出。 @@ -302,6 +334,18 @@ Options.Transport 可以借用原生 RoundTripper 以支持特定代理和证书 本库不是旧包的 import 兼容层。旧 Response 类型、HTTP 状态映射、SSE 事件、请求后 Hook、认证和文档展示都需要显式适配,见 [迁移清单](migration.md)。 +### 9.1 完整装配示例 + +```sh +go run ./examples/application -config examples/application/config.yml +``` + +[完整示例](../examples/application/main.go) 和 [示例配置](../examples/application/config.yml) 演示:配置日志 → 创建可选数据库/Redis → 创建复用出站客户端 → 注册 Controller/健康检查 → 全部成功后 SetReady(true) → 监听。默认配置无需数据库或 Redis 即可运行,取消配置注释后启用真实依赖;配置了任一依赖但创建失败必须停止启动。 + +装配中的资源先由局部 resources 持有,失败关闭已创建部分;示例没有全局服务容器或运行期查找依赖。注册/监听/Serve 提前失败也会排空 HTTP;正常退出先置未就绪、取消并等待处理函数结束,再逆序关闭出站空闲池、Redis、数据库,最后关闭日志。 + +该示例没有 Worker;消费应用有 Worker 时必须在连接释放前取消并等待它们完成。示例及测试覆盖无外部依赖启动、失败回收和退出,真实 MySQL 与业务插件仍须集成环境验证。 + ## 10. 文档同步与验收 任何能力新增、移除或行为变化,在同一提交中完成:能力表、所属章节、公开 API 用法、配置及缺省值、所有权/退出约束、兼容影响、示例或实际验证说明。删除能力须同时移除陈旧命令和安装说明;重命名须核对所有链接。README 和 AGENTS 只保留本指南入口,技术约束唯一维护在规约正文。 diff --git a/docs/integration-optimization-review.md b/docs/integration-optimization-review.md index 5f558c4..2cbd788 100644 --- a/docs/integration-optimization-review.md +++ b/docs/integration-optimization-review.md @@ -52,6 +52,8 @@ 这些改动有明确现有调用,不引入通用生命周期容器、泛型 Option 解析器或动态策略注册表。性能收益只确认移除了重复工作,没有据此宣称已测得吞吐提升。 +核心 P1 后续补齐:字段级安全提示、请求 Context 诊断、普通 Controller 合作式预算、存活/就绪探测和完整资源装配示例均已提供,具体契约以 [接入使用指南](getting-started.md) 为准。 + ## 4. 适合继续整合,但本轮不扩大的范围 | 优先级 | 建议 | 边界与依据 | diff --git a/docs/migration.md b/docs/migration.md index e96dde6..4386648 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -26,12 +26,19 @@ - 请求 `default` tag 延续原有 go-defaults 行为:标量零值可能被视为缺省。对需区分未传和显式零值的字段使用指针,接入前补对应用例;不声称库已实现 JSON 全字段存在性跟踪。 - 默认响应耗时字段为 cost_ms。原项目响应字段配置、业务错误状态推导及业务 HTTP 中间件需要在回接阶段明确适配并对照实际协议。 - 库通过受信任中间件生成自己的 request_id/trace_id,不信任客户端同名请求头;应用跨服务传播协议另行明确。 -- 当前不包含旧 SSE 握手/结束事件、请求后业务 Hook、反射路由超时、no-login 和 rate-limit 语义;检测到旧 tag 明确拒绝。流式服务先使用原生 Gin Handler 适配,不静默改变认证或输出协议。 +- 当前不包含旧 SSE 握手/结束事件、请求后业务 Hook、no-login 和 rate-limit 语义;检测到旧 tag 明确拒绝。流式服务先使用原生 Gin Handler 适配,不静默改变认证或输出协议。 - OpenAPI/Scalar 展示、pprof、CORS 和限流策略尚未迁入本库;应用可在显式 Gin 中间件与路由处装配。文档侧读取 Routes 快照,不要求业务 DTO 引入运行框架。 - Redis 实例名、Key、缓存、租约、队列和锁留在应用。Redis Open 返回原生客户端,正常关闭错误由应用首次接收并分类记录。 - 审计插件由应用通过 database.Options.Plugins 显式安装。基础库没有审计 Model、表名和后台身份语义。 - 库保留原生 GORM 方言扩展点;SQLite 用于本地回归,MySQL 的真实连接、方言和项目审计仍需集成环境验证。 +## P1 能力补齐后的兼容说明 + +- 字段约束失败仍返回 HTTP 400,但新增 data.fields 安全提示,message 为 Validation failed;格式绑定错误仍使用通用安全提示。 +- 新增 RequestTimeoutMS 普通 Controller 合作式预算,默认 30000 毫秒;需要保留无预算行为时显式设零。max-exec-time 按秒覆盖,0 禁用,不等同于旧缓冲响应超时中间件。原生 Handle/SSE 保持显式截止方式。 +- 新增 RegisterHealth 与 SetReady,未显式完成就绪装配前 ready 返回 503,依赖检查复用原生池。 +- Context 校验入口为 Form.ValidateContext;旧 Validate 保留供无请求场景兼容。完整装配示例和约束统一见接入指南。 + ## 出站客户端接入边界 新增 httpclient 的 API 不与旧 network/httpclient/define.Response 兼容。先接入无业务码解析的普通调用,再按供应商适配:保留原始 HTTP 状态及字节,由应用映射旧 Response、成功码和任务失败信息。任务提交、查询、搜索和下载不能仅替换 import 路径。 diff --git a/examples/application/config.yml b/examples/application/config.yml new file mode 100644 index 0000000..340b364 --- /dev/null +++ b/examples/application/config.yml @@ -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} diff --git a/examples/application/main.go b/examples/application/main.go new file mode 100644 index 0000000..cf12364 --- /dev/null +++ b/examples/application/main.go @@ -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...) +} diff --git a/examples/application/main_test.go b/examples/application/main_test.go new file mode 100644 index 0000000..62b40a5 --- /dev/null +++ b/examples/application/main_test.go @@ -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) + } +} diff --git a/http/budget.go b/http/budget.go new file mode 100644 index 0000000..8619c30 --- /dev/null +++ b/http/budget.go @@ -0,0 +1,33 @@ +package http + +import ( + "context" + "errors" + "net/http" + + failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "github.com/gin-gonic/gin" +) + +// finishCanceled 在合作式预算结束后统一返回超时响应,保留已分类错误的日志语义。 +// 入参:ctx 为当前请求,cause 为已接收的下层错误,允许 nil。 +// 返回:上下文结束并应停止当前流程时为 true;客户端取消时不继续写响应。 +func (s *Server) finishCanceled(ctx *gin.Context, cause error) bool { + err := ctx.Request.Context().Err() + if err == nil { + return false + } + if cause == nil { + cause = err + } + code, summary := codeRequestCancelled, "HTTP request cancelled" + if errors.Is(err, context.DeadlineExceeded) { + code, summary = codeRequestTimeout, "HTTP request budget exceeded" + } + classified := failure.WrapContext(ctx.Request.Context(), code, summary, cause) + if errors.Is(err, context.DeadlineExceeded) { + s.writeResult(ctx, nil, classified, http.StatusGatewayTimeout) + } + ctx.Abort() + return true +} diff --git a/http/context_flow_test.go b/http/context_flow_test.go new file mode 100644 index 0000000..cef45af --- /dev/null +++ b/http/context_flow_test.go @@ -0,0 +1,161 @@ +package http + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "git.zhangdeman.cn/github/ginframework/database" + "git.zhangdeman.cn/github/ginframework/diagnostic" + "git.zhangdeman.cn/github/ginframework/httpclient" + "git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver" + "git.zhangdeman.cn/github/ginframework/logger" + "git.zhangdeman.cn/github/ginframework/redis/commandlog" + "github.com/gin-gonic/gin" + redisclient "github.com/redis/go-redis/v9" + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" + "gorm.io/driver/sqlite" +) + +type flowTransport func(*http.Request) (*http.Response, error) + +func (f flowTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +type flowForm struct { + Meta `path:"/context-flow" method:"GET"` + Bad bool `form:"bad"` +} +type flowController struct { + database *database.Connection + redis *redisclient.Client + outbound *httpclient.Client +} + +func (c *flowController) Run(ctx *gin.Context, input *flowForm) (*exampleOutput, error) { + parent := ctx.Request.Context() + if err := c.database.Session(parent).Exec("SELECT 1").Error; err != nil { + return nil, err + } + if err := c.redis.Ping(parent).Err(); err != nil { + return nil, err + } + target := "https://example.test/ok" + if input.Bad { + target = "https://example.test/bad" + } + response, err := c.outbound.Send(parent, httpclient.Request{URL: target}) + if err != nil { + return nil, err + } + var ( + output exampleOutput + ) + if err = response.DecodeJSON(&output); err != nil { + return nil, err + } + return &output, nil +} + +func TestHTTPDatabaseRedisOutboundKeepOneDiagnosticSnapshot(t *testing.T) { + directory := t.TempDir() + if _, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: directory, UseJSON: true}); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = logger.CloseOutputs() }) + sqlCore, sqlLogs := observer.New(zap.InfoLevel) + connection, err := database.Open(context.Background(), database.Config{Name: "test"}, database.Options{Dialector: sqlite.Open(":memory:"), Logger: zap.New(sqlCore)}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := connection.Close(); err != nil { + t.Error(err) + } + }) + redis := redisserver.New(t, 3) + redisCore, redisLogs := observer.New(zap.InfoLevel) + redis.AddHook(commandlog.New(zap.New(redisCore), "test")) + outboundCore, outboundLogs := observer.New(zap.InfoLevel) + client, err := httpclient.New(httpclient.Config{}, httpclient.Options{Logger: zap.New(outboundCore), Transport: flowTransport(func(r *http.Request) (*http.Response, error) { + if diagnostic.From(r.Context()).TraceID == "" { + return nil, errors.New("outbound context lost") + } + if _, ok := r.Context().Deadline(); !ok { + return nil, errors.New("outbound budget lost") + } + body := `{"name":"ok"}` + if r.URL.Path == "/bad" { + body = `{"private-token":` + } + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil + })}) + if err != nil { + t.Fatal(err) + } + server, err := NewServer(Config{}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.Group("", nil, &flowController{database: connection, redis: redis, outbound: client}); err != nil { + t.Fatal(err) + } + var ( + traces []string + ) + for _, bad := range []bool{false, true} { + path := "/context-flow" + if bad { + path += "?bad=true" + } + recorder := httptest.NewRecorder() + server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", path, nil)) + expected := 200 + if bad { + expected = 500 + } + if recorder.Code != expected { + t.Fatalf("flow status=%d: %s", recorder.Code, recorder.Body.String()) + } + traces = append(traces, recorder.Header().Get("X-Request-ID")) + } + for _, trace := range traces { + if trace == "" { + t.Fatal("missing HTTP trace") + } + for name, logs := range map[string]*observer.ObservedLogs{"sql": sqlLogs, "redis": redisLogs, "outbound": outboundLogs} { + found := false + for _, entry := range logs.All() { + raw, _ := json.Marshal(entry.ContextMap()) + if strings.Contains(string(raw), trace) { + found = true + break + } + } + if !found { + t.Fatalf("%s lost HTTP diagnostic snapshot %s", name, trace) + } + } + } + if err = logger.CloseOutputs(); err != nil { + t.Fatal(err) + } + paths, _ := filepath.Glob(filepath.Join(directory, "*")) + if len(paths) != 1 { + t.Fatal("source error log missing") + } + raw, err := os.ReadFile(paths[0]) + if err != nil { + t.Fatal(err) + } + if strings.Count(strings.TrimSpace(string(raw)), "\n") != 0 || !strings.Contains(string(raw), traces[1]) || strings.Contains(string(raw), "private-token") { + t.Fatalf("outbound decode error lost context or logged twice: %s", raw) + } +} diff --git a/http/health.go b/http/health.go new file mode 100644 index 0000000..0391f58 --- /dev/null +++ b/http/health.go @@ -0,0 +1,103 @@ +package http + +import ( + "context" + "errors" + "net/http" + "strings" + "time" + + failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "github.com/gin-gonic/gin" +) + +// ReadinessCheck 是应用声明的依赖探测,不暴露驱动错误到健康响应。 +type ReadinessCheck struct { + Name string `json:"name" dc:"安全的依赖名称,不包含连接地址或凭据"` + Check func(context.Context) error `json:"-" dc:"遵守传入上下文的探测函数,不负责创建连接"` +} + +// HealthOptions 描述固定的启动期探测清单。 +type HealthOptions struct { + TimeoutMS int64 `json:"timeout_ms" dc:"一次就绪检查的总预算毫秒,缺省 1000"` + Checks []ReadinessCheck `json:"-" dc:"应用已创建资源的探测列表,注册时复制"` +} + +type checkResult struct { + Name string `json:"name" dc:"应用声明的安全依赖名称"` + Ready bool `json:"ready" dc:"依赖是否通过检查,不携带原始原因"` +} + +type healthResult struct { + Status string `json:"status" dc:"ok 或 not_ready"` + Checks []checkResult `json:"checks,omitempty" dc:"就绪探测结果,不输出连接信息"` +} + +// RegisterHealth 批次注册 GET {prefix}/live 和 GET {prefix}/ready。 +// 入参:prefix 为完整路径前缀,空值使用 /_health;options 为探测配置。 +// 返回:配置、路由冲突或注册已冻结时返回错误,不部分注册。 +// 隐式逻辑:就绪初始为 false,应用完成全部装配后显式调用 SetReady(true)。 +func (s *Server) RegisterHealth(prefix string, options HealthOptions) error { + if prefix == "" { + prefix = "/_health" + } + prefix = strings.TrimRight(prefix, "/") + if !strings.HasPrefix(prefix, "/") || strings.ContainsAny(prefix, ":*?#") || options.TimeoutMS < 0 || options.TimeoutMS > int64((1<<63-1)/time.Millisecond) { + return failure.Wrap(codeHealthConfig, "validate health endpoint configuration failed", errors.New("invalid health prefix or probe budget")) + } + if options.TimeoutMS == 0 { + options.TimeoutMS = 1000 + } + options.Checks = append([]ReadinessCheck(nil), options.Checks...) + names := make(map[string]bool, len(options.Checks)) + for _, check := range options.Checks { + if strings.TrimSpace(check.Name) == "" || check.Check == nil || names[check.Name] { + return failure.Wrap(codeHealthConfig, "validate readiness check configuration failed", errors.New("check names and callbacks must be unique and non-empty")) + } + names[check.Name] = true + } + return s.commit([]route{ + {meta: Metadata{Method: http.MethodGet, Path: prefix + "/live", Summary: "Process liveness", Tag: "health"}, handlers: []gin.HandlerFunc{func(ctx *gin.Context) { ctx.JSON(http.StatusOK, healthResult{Status: "ok"}) }}}, + {meta: Metadata{Method: http.MethodGet, Path: prefix + "/ready", Summary: "Service readiness", Tag: "health"}, handlers: []gin.HandlerFunc{s.readiness(options)}}, + }) +} + +// SetReady 设置应用装配/排空阶段的就绪信号,不代替依赖探测。 +// 入参:ready 为应用是否允许接收业务流量;停止时框架自动置 false。 +func (s *Server) SetReady(ready bool) { s.ready.Store(ready) } + +// readiness 创建使用固定探测快照的处理器,不建立后台任务或动态注册表。 +// 入参:options 为已经校验的检查清单和总预算。 +// 返回:不泄露检查原始错误的 Gin Handler;回调必须响应取消。 +func (s *Server) readiness(options HealthOptions) gin.HandlerFunc { + return func(ctx *gin.Context) { + if !s.ready.Load() { + ctx.JSON(http.StatusServiceUnavailable, healthResult{Status: "not_ready"}) + return + } + probe, cancel := context.WithTimeout(ctx.Request.Context(), time.Duration(options.TimeoutMS)*time.Millisecond) + defer cancel() + result := healthResult{Status: "ok", Checks: make([]checkResult, 0, len(options.Checks))} + for _, check := range options.Checks { + err := probe.Err() + if err == nil { + err = check.Check(probe) + } + if err == nil { + err = probe.Err() + } + passed := err == nil + if !passed { + _ = failure.WrapContext(probe, codeReadinessCheck, "check service readiness failed", err) + result.Status = "not_ready" + } + result.Checks = append(result.Checks, checkResult{Name: check.Name, Ready: passed}) + } + status := http.StatusOK + if !s.ready.Load() || result.Status != "ok" { + status = http.StatusServiceUnavailable + result.Status = "not_ready" + } + ctx.JSON(status, result) + } +} diff --git a/http/p1_test.go b/http/p1_test.go new file mode 100644 index 0000000..f8ba5b7 --- /dev/null +++ b/http/p1_test.go @@ -0,0 +1,277 @@ +package http + +import ( + "context" + "encoding/json" + "errors" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "git.zhangdeman.cn/github/ginframework/diagnostic" + "git.zhangdeman.cn/github/ginframework/http/request" + "git.zhangdeman.cn/github/ginframework/logger" + "github.com/gin-gonic/gin" + "github.com/go-playground/validator/v10" +) + +type profileInput struct { + Email string `json:"email" binding:"required,email" err:"Enter a valid email address"` + Secret string `json:"secret" binding:"oneof=allowed"` +} +type validationForm struct { + Meta `path:"/validate" method:"POST"` + Profile profileInput `json:"profile" binding:"required"` + Items []profileInput `json:"items" binding:"dive"` + Attributes map[string]profileInput `json:"attributes" binding:"dive"` +} +type validationController struct{} + +func (*validationController) Validate(*gin.Context, *validationForm) (*exampleOutput, error) { + return &exampleOutput{}, nil +} + +func TestFieldErrorsArePublicSafeAndKeepNativeCause(t *testing.T) { + server, err := NewServer(Config{}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.Group("", nil, &validationController{}); err != nil { + t.Fatal(err) + } + body := `{"profile":{"email":"private-invalid-email","secret":"private-token"},"items":[{"email":"bad","secret":"allowed"}],"attributes":{"private-map-key":{"email":"bad","secret":"allowed"}}}` + recorder := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/validate", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + server.Handler().ServeHTTP(recorder, req) + if recorder.Code != 400 { + t.Fatalf("status=%d %s", recorder.Code, recorder.Body.String()) + } + var ( + output struct { + Data request.ValidationDetails `json:"data"` + } + ) + if err = json.Unmarshal(recorder.Body.Bytes(), &output); err != nil { + t.Fatal(err) + } + fields := map[string]request.FieldError{} + for _, field := range output.Data.Fields { + fields[field.Field] = field + } + if fields["profile.email"].Rule != "email" || fields["profile.email"].Message != "Enter a valid email address" || fields["items[].email"].Rule != "email" || fields["attributes[].email"].Rule != "email" { + t.Fatalf("field names lost: %+v", fields) + } + for _, hidden := range []string{"private-invalid-email", "private-token", "private-map-key", "oneof=allowed", "validationForm"} { + if strings.Contains(recorder.Body.String(), hidden) { + t.Fatalf("validation leaked %s", hidden) + } + } + var ( + value validationForm + ) + cause := request.Form.ValidateContext(context.Background(), &value) + var ( + native validator.ValidationErrors + ) + if !errors.As(cause, &native) { + t.Fatalf("native validator cause lost: %v", cause) + } +} + +func TestBindingFailureLogsTrustedContextOnce(t *testing.T) { + directory := t.TempDir() + if _, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: directory, UseJSON: true}); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = logger.CloseOutputs() }) + server, err := NewServer(Config{}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.Group("", nil, &validationController{}); err != nil { + t.Fatal(err) + } + recorder := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/validate", strings.NewReader(`{"private-token":`)) + req.Header.Set("Content-Type", "application/json") + server.Handler().ServeHTTP(recorder, req) + trace := recorder.Header().Get("X-Request-ID") + if err = logger.CloseOutputs(); err != nil { + t.Fatal(err) + } + paths, _ := filepath.Glob(filepath.Join(directory, "*")) + if len(paths) != 1 { + t.Fatal("log missing") + } + raw, err := os.ReadFile(paths[0]) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(raw)), "\n") + if len(lines) != 1 || trace == "" { + t.Fatalf("duplicate or missing error log: %s", raw) + } + var ( + entry map[string]any + ) + if err = json.Unmarshal([]byte(lines[0]), &entry); err != nil { + t.Fatal(err) + } + if entry["trace_id"] != trace || entry["uri"] != "/validate" || strings.Contains(string(raw), "private-token") { + t.Fatalf("unsafe or missing context: %s", raw) + } +} + +type budgetForm struct { + Meta `path:"/budget" method:"GET"` +} +type disabledBudgetForm struct { + Meta `path:"/unlimited" method:"GET" max-exec-time:"0"` +} +type budgetController struct { + cancelled chan struct{} + release chan struct{} +} + +func (c *budgetController) Wait(ctx *gin.Context, _ *budgetForm) (*exampleOutput, error) { + <-ctx.Request.Context().Done() + close(c.cancelled) + <-c.release + return nil, ctx.Request.Context().Err() +} +func (c *budgetController) Unlimited(ctx *gin.Context, _ *disabledBudgetForm) (*exampleOutput, error) { + if _, exists := ctx.Request.Context().Deadline(); exists { + return nil, errors.New("disabled route still has a deadline") + } + return &exampleOutput{Name: "ok"}, nil +} + +func TestCooperativeBudgetReturns504AfterHandlerStops(t *testing.T) { + budget := int64(20) + server, err := NewServer(Config{RequestTimeoutMS: &budget}, Options{}) + if err != nil { + t.Fatal(err) + } + controller := &budgetController{cancelled: make(chan struct{}), release: make(chan struct{})} + if err = server.Group("", nil, controller); err != nil { + t.Fatal(err) + } + budget = 1 // 构造时必须复制配置,调用方修改不改变当前实例。 + recorder := httptest.NewRecorder() + done := make(chan struct{}) + go func() { + defer close(done) + server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/budget", nil)) + }() + select { + case <-controller.cancelled: + case <-time.After(time.Second): + t.Fatal("request budget did not cancel handler") + } + select { + case <-done: + t.Fatal("request returned while handler was still using dependencies") + default: + } + close(controller.release) + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("request did not complete") + } + if recorder.Code != 504 || !strings.Contains(recorder.Body.String(), "Gateway Timeout") { + t.Fatalf("unsafe timeout response: %d %s", recorder.Code, recorder.Body.String()) + } + recorder = httptest.NewRecorder() + server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/unlimited", nil)) + if recorder.Code != 200 { + t.Fatalf("route override failed: %s", recorder.Body.String()) + } +} + +func TestHealthReadinessStateAndDependencyFailure(t *testing.T) { + var ( + degraded atomic.Bool + checks atomic.Int32 + ) + server, err := NewServer(Config{}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.RegisterHealth("/_health", HealthOptions{Checks: []ReadinessCheck{{Name: "database", Check: func(ctx context.Context) error { + checks.Add(1) + if diagnostic.From(ctx).TraceID == "" { + t.Error("health context lost") + } + if degraded.Load() { + return errors.New("private-password and address") + } + return nil + }}}}); err != nil { + t.Fatal(err) + } + handler := server.Handler() + probe := func(path string) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest("GET", path, nil)) + return recorder + } + if probe("/_health/live").Code != 200 || probe("/_health/ready").Code != 503 || checks.Load() != 0 { + t.Fatal("uninitialized service was ready or liveness depended on DB") + } + server.SetReady(true) + if probe("/_health/ready").Code != 200 { + t.Fatal("initialized service not ready") + } + degraded.Store(true) + response := probe("/_health/ready") + if response.Code != 503 || strings.Contains(response.Body.String(), "private-password") { + t.Fatal("dependency failure was exposed or ignored") + } + if probe("/_health/live").Code != 200 { + t.Fatal("dependency outage incorrectly failed liveness") + } + server.SetReady(false) + if probe("/_health/ready").Code != 503 { + t.Fatal("draining service remained ready") + } + if err = server.RegisterHealth("/late", HealthOptions{}); err == nil { + t.Fatal("health registration was not frozen") + } +} + +func TestReadinessBudgetAndNativeStreamAreSeparate(t *testing.T) { + budget := int64(1) + server, err := NewServer(Config{RequestTimeoutMS: &budget}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.RegisterHealth("/_health", HealthOptions{TimeoutMS: 10, Checks: []ReadinessCheck{{Name: "slow", Check: func(ctx context.Context) error { <-ctx.Done(); return ctx.Err() }}}}); err != nil { + t.Fatal(err) + } + if err = server.Handle("GET", "/native", func(ctx *gin.Context) { + if _, exists := ctx.Request.Context().Deadline(); exists { + t.Error("native route received controller budget") + } + ctx.Status(204) + }); err != nil { + t.Fatal(err) + } + server.SetReady(true) + handler := server.Handler() + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/_health/ready", nil)) + if recorder.Code != 503 { + t.Fatal("expired readiness was successful") + } + recorder = httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/native", nil)) + if recorder.Code != 204 { + t.Fatal("native route changed") + } +} diff --git a/http/request/body.go b/http/request/body.go index 00c0603..ffe048e 100644 --- a/http/request/body.go +++ b/http/request/body.go @@ -24,18 +24,18 @@ const ( // 返回:正文副本视图;失败保留读取错误或 http.MaxBytesError 原因链。 func ReadBodyWithLimit(ctx *gin.Context, limit int64) ([]byte, error) { if ctx == nil || ctx.Request == nil { - return nil, fault.Wrap(codeBodyContext, "validate request body context failed", errors.New("request context is missing")) + return nil, fault.WrapContext(contextOf(ctx), codeBodyContext, "validate request body context failed", errors.New("request context is missing")) } if limit <= 0 { limit = DefaultMaxBodyBytes } if limit == 1<<63-1 { - return nil, fault.Wrap(codeBodyLarge, "validate request body limit failed", errors.New("body limit exceeds supported range")) + return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body limit failed", errors.New("body limit exceeds supported range")) } if cached, exists := ctx.Get(bodyCacheKey); exists { body := cached.([]byte) if int64(len(body)) > limit { - return nil, fault.Wrap(codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) + return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) } ctx.Request.Body = io.NopCloser(bytes.NewReader(body)) return body, nil @@ -49,10 +49,10 @@ func ReadBodyWithLimit(ctx *gin.Context, limit int64) ([]byte, error) { _ = original.Close() ctx.Request.Body = io.NopCloser(bytes.NewReader(body)) if err != nil { - return nil, fault.Wrap(codeBodyRead, "read request body failed", err) + return nil, fault.WrapContext(contextOf(ctx), codeBodyRead, "read request body failed", err) } if int64(len(body)) > limit { - return nil, fault.Wrap(codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) + return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) } ctx.Set(bodyCacheKey, body) return body, nil diff --git a/http/request/context.go b/http/request/context.go new file mode 100644 index 0000000..c079867 --- /dev/null +++ b/http/request/context.go @@ -0,0 +1,22 @@ +package request + +import ( + "context" + "github.com/gin-gonic/gin" +) + +// contextOf 在请求适配边界提取标准上下文,不读取客户端身份或诊断头。 +// 入参:ctx 为 Gin 或标准上下文,允许 nil 表示没有请求来源。 +// 返回:保留取消与可信诊断的标准上下文,无来源时使用背景上下文。 +func contextOf(ctx context.Context) context.Context { + if request, ok := ctx.(*gin.Context); ok { + if request != nil && request.Request != nil { + return request.Request.Context() + } + return context.Background() + } + if ctx == nil { + return context.Background() + } + return ctx +} diff --git a/http/request/form.go b/http/request/form.go index 6d9f807..0025828 100644 --- a/http/request/form.go +++ b/http/request/form.go @@ -2,6 +2,7 @@ package request import ( "bytes" + "context" "encoding/json" "errors" "fmt" @@ -61,13 +62,13 @@ type form struct{} // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 func (formInstance *form) Parse(ctx *gin.Context, receiver any, optionList ...ParseOptionFunc) (resultError error) { - defer fault.Capture(&resultError, CodeFormParse1, "parse failed") + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormParse1, "parse failed") if err := formInstance.Bind(ctx, receiver, optionList...); err != nil { return err } defaults.SetDefaults(receiver) - return formInstance.Validate(receiver) + return formInstance.ValidateContext(contextOf(ctx), receiver) } // Bind 按 URI → Query → Body 的顺序绑定请求参数,但不设置默认值或执行校验。 @@ -80,21 +81,21 @@ func (formInstance *form) Parse(ctx *gin.Context, receiver any, optionList ...Pa // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...ParseOptionFunc) (resultError error) { - defer fault.Capture(&resultError, CodeFormBind5, "bind failed") + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormBind5, "bind failed") if ctx == nil || ctx.Request == nil { - return fault.Wrap(CodeFormBind1, "bind failed", errors.New("invalid gin request context")) + return fault.WrapContext(contextOf(ctx), CodeFormBind1, "bind failed", errors.New("invalid gin request context")) } - if err := validateReceiver(receiver); err != nil { + if err := validateReceiver(contextOf(ctx), receiver); err != nil { return err } option := buildParseOption(optionList...) if err := bindURI(ctx, receiver); err != nil { - return fault.Wrap(CodeFormBind2, "bind failed", fmt.Errorf("bind URI parameters: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBind2, "bind failed", fmt.Errorf("bind URI parameters: %w", err)) } if err := binding.MapFormWithTag(receiver, ctx.Request.URL.Query(), "form"); err != nil { - return fault.Wrap(CodeFormBind3, "bind failed", fmt.Errorf("bind query parameters: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBind3, "bind failed", fmt.Errorf("bind query parameters: %w", err)) } method := strings.ToUpper(ctx.Request.Method) @@ -105,7 +106,7 @@ func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...Par case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: return formInstance.bindBody(ctx, receiver, option.MaxBodyBytes) default: - return fault.Wrap(CodeFormBind4, "bind failed", fmt.Errorf("%s: request method is not supported", method)) + return fault.WrapContext(contextOf(ctx), CodeFormBind4, "bind failed", fmt.Errorf("%s: request method is not supported", method)) } } @@ -116,16 +117,21 @@ func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...Par // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func (*form) Validate(receiver any) (resultError error) { - defer fault.Capture(&resultError, CodeFormValidate1, "validate failed") +func (f *form) Validate(receiver any) error { + return f.ValidateContext(context.Background(), receiver) +} +// ValidateContext 使用可信调用上下文执行一次最终校验,返回安全的字段级错误。 +// 入参:ctx 为标准上下文,receiver 为绑定及可信注入完成的 Form。 +// 返回:字段约束失败返回 ValidationError;错误链与源头日志保留原始校验原因。 +func (*form) ValidateContext(ctx context.Context, receiver any) error { if binding.Validator == nil { return nil } - // 与 RegisterValidation 共用读写锁,保证运行期规则注册不会和请求校验并发修改 validator 缓存。 requestValidatorLock.RLock() defer requestValidatorLock.RUnlock() - return binding.Validator.ValidateStruct(receiver) + err := binding.Validator.ValidateStruct(receiver) + return validationResult(contextOf(ctx), receiver, err) } // bindBody 按请求媒体类型绑定正文,保留正文缓存与大小限制。 @@ -138,7 +144,7 @@ func (*form) Validate(receiver any) (resultError error) { // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes int64) (resultError error) { - defer fault.Capture(&resultError, CodeFormBindBody10, "bind body failed") + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormBindBody10, "bind body failed") bodyData, err := ReadBodyWithLimit(ctx, maxBodyBytes) if err != nil { @@ -151,7 +157,7 @@ func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes contentType := ctx.GetHeader("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { - return fault.Wrap(CodeFormBindBody1, "bind body failed", fmt.Errorf("%w: invalid Content-Type %q: %v", ErrUnsupportedMediaType, contentType, err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody1, "bind body failed", fmt.Errorf("%w: invalid Content-Type %q: %v", ErrUnsupportedMediaType, contentType, err)) } mediaType = strings.ToLower(mediaType) @@ -165,35 +171,35 @@ func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes decoder.DisallowUnknownFields() } if err = decoder.Decode(receiver); err != nil { - return fault.Wrap(CodeFormBindBody2, "bind body failed", fmt.Errorf("decode JSON body: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody2, "bind body failed", fmt.Errorf("decode JSON body: %w", err)) } if err = decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { - return fault.Wrap(CodeFormBindBody3, "bind body failed", errors.New("decode JSON body: multiple JSON values are not allowed")) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody3, "bind body failed", errors.New("decode JSON body: multiple JSON values are not allowed")) } return nil case mediaType == "application/x-www-form-urlencoded": values, parseErr := url.ParseQuery(string(bodyData)) if parseErr != nil { - return fault.Wrap(CodeFormBindBody4, "bind body failed", fmt.Errorf("parse form body: %w", parseErr)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody4, "bind body failed", fmt.Errorf("parse form body: %w", parseErr)) } if err = binding.MapFormWithTag(receiver, values, "form"); err != nil { - return fault.Wrap(CodeFormBindBody5, "bind body failed", fmt.Errorf("bind form body: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody5, "bind body failed", fmt.Errorf("bind form body: %w", err)) } return nil case mediaType == "multipart/form-data": // ReadBodyWithLimit 已恢复 Request.Body,这里可继续交给 net/http 按 boundary 解析。 if err = ctx.Request.ParseMultipartForm(maxBodyBytes); err != nil { - return fault.Wrap(CodeFormBindBody6, "bind body failed", fmt.Errorf("parse multipart body: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody6, "bind body failed", fmt.Errorf("parse multipart body: %w", err)) } if err = binding.MapFormWithTag(receiver, ctx.Request.MultipartForm.Value, "form"); err != nil { - return fault.Wrap(CodeFormBindBody7, "bind body failed", fmt.Errorf("bind multipart values: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody7, "bind body failed", fmt.Errorf("bind multipart values: %w", err)) } - if err = bindMultipartFiles(receiver, ctx.Request.MultipartForm.File); err != nil { - return fault.Wrap(CodeFormBindBody8, "bind body failed", fmt.Errorf("bind multipart files: %w", err)) + if err = bindMultipartFiles(contextOf(ctx), receiver, ctx.Request.MultipartForm.File); err != nil { + return fault.WrapContext(contextOf(ctx), CodeFormBindBody8, "bind body failed", fmt.Errorf("bind multipart files: %w", err)) } return nil default: - return fault.Wrap(CodeFormBindBody9, "bind body failed", fmt.Errorf("%w: %s", ErrUnsupportedMediaType, mediaType)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody9, "bind body failed", fmt.Errorf("%w: %s", ErrUnsupportedMediaType, mediaType)) } } @@ -222,19 +228,20 @@ func buildParseOption(optionList ...ParseOptionFunc) ParseOption { // validateReceiver 检查请求绑定目标是否为可写的非空结构体指针。 // // 入参: +// - ctx:当前可信请求或内部调用上下文。 // - receiver:需要写入绑定结果的具体结构体指针。 // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func validateReceiver(receiver any) (resultError error) { - defer fault.Capture(&resultError, CodeValidateReceiver3, "validate receiver failed") +func validateReceiver(ctx context.Context, receiver any) (resultError error) { + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeValidateReceiver3, "validate receiver failed") if receiver == nil { - return fault.Wrap(CodeValidateReceiver1, "validate receiver failed", errors.New("request receiver cannot be nil")) + return fault.WrapContext(contextOf(ctx), CodeValidateReceiver1, "validate receiver failed", errors.New("request receiver cannot be nil")) } value := reflect.ValueOf(receiver) if value.Kind() != reflect.Ptr || value.IsNil() || value.Elem().Kind() != reflect.Struct { - return fault.Wrap(CodeValidateReceiver2, "validate receiver failed", fmt.Errorf("request receiver must be a non-nil pointer, got %T", receiver)) + return fault.WrapContext(contextOf(ctx), CodeValidateReceiver2, "validate receiver failed", fmt.Errorf("request receiver must be a non-nil pointer, got %T", receiver)) } return nil } @@ -248,7 +255,7 @@ func validateReceiver(receiver any) (resultError error) { // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 func bindURI(ctx *gin.Context, receiver any) (resultError error) { - defer fault.Capture(&resultError, CodeBindURI1, "bind u r i failed") + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeBindURI1, "bind u r i failed") uriValues := make(map[string][]string, len(ctx.Params)) for _, param := range ctx.Params { @@ -260,34 +267,36 @@ func bindURI(ctx *gin.Context, receiver any) (resultError error) { // bindMultipartFiles 将常见 multipart.FileHeader 字段绑定到请求结构体。 // // 入参: +// - ctx:当前可信请求或内部调用上下文。 // - receiver:需要写入绑定结果的具体结构体指针。 // - files:本次上传解析得到的文件头列表。 // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func bindMultipartFiles(receiver any, files map[string][]*multipart.FileHeader) (resultError error) { - defer fault.Capture(&resultError, CodeBindMultipartFiles1, "bind multipart files failed") +func bindMultipartFiles(ctx context.Context, receiver any, files map[string][]*multipart.FileHeader) (resultError error) { + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeBindMultipartFiles1, "bind multipart files failed") - return walkMultipartFields(reflect.ValueOf(receiver), files) + return walkMultipartFields(ctx, reflect.ValueOf(receiver), files) } // walkMultipartFields 递归绑定表单字段及文件,保留嵌入和可选字段语义。 // // 入参: +// - ctx:当前可信请求或内部调用上下文。 // - value:需要按当前方法约定检查或转换的值。 // - files:本次上传解析得到的文件头列表。 // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func walkMultipartFields(value reflect.Value, files map[string][]*multipart.FileHeader) (resultError error) { - defer fault.Capture(&resultError, CodeWalkMultipartFields2, "walk multipart fields failed") +func walkMultipartFields(ctx context.Context, value reflect.Value, files map[string][]*multipart.FileHeader) (resultError error) { + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeWalkMultipartFields2, "walk multipart fields failed") if value.Kind() == reflect.Ptr { if value.IsNil() { // 不为仅可能存在的文件字段创建业务对象;非 nil 的嵌套结构仍会继续绑定。 return nil } - return walkMultipartFields(value.Elem(), files) + return walkMultipartFields(ctx, value.Elem(), files) } if value.Kind() != reflect.Struct { return nil @@ -308,13 +317,13 @@ func walkMultipartFields(value reflect.Value, files map[string][]*multipart.File fieldName = structField.Name } if fileList := files[fieldName]; len(fileList) > 0 { - if err := setMultipartFileValue(fieldValue, fileList); err != nil { - return fault.Wrap(CodeWalkMultipartFields1, "walk multipart fields failed", fmt.Errorf("field %s: %w", structField.Name, err)) + if err := setMultipartFileValue(ctx, fieldValue, fileList); err != nil { + return fault.WrapContext(contextOf(ctx), CodeWalkMultipartFields1, "walk multipart fields failed", fmt.Errorf("field %s: %w", structField.Name, err)) } continue } if structField.Anonymous || indirectKind(fieldValue.Type()) == reflect.Struct { - if err := walkMultipartFields(fieldValue, files); err != nil { + if err := walkMultipartFields(ctx, fieldValue, files); err != nil { return err } } @@ -325,16 +334,17 @@ func walkMultipartFields(value reflect.Value, files map[string][]*multipart.File // setMultipartFileValue 按目标字段类型写入单个或多个上传文件。 // // 入参: +// - ctx:当前可信请求或内部调用上下文。 // - fieldValue:需要绑定或检查的可写字段反射值。 // - files:本次上传解析得到的文件头列表。 // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func setMultipartFileValue(fieldValue reflect.Value, files []*multipart.FileHeader) (resultError error) { - defer fault.Capture(&resultError, CodeSetMultipartFileValue3, "set multipart file value failed") +func setMultipartFileValue(ctx context.Context, fieldValue reflect.Value, files []*multipart.FileHeader) (resultError error) { + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeSetMultipartFileValue3, "set multipart file value failed") if !fieldValue.CanSet() { - return fault.Wrap(CodeSetMultipartFileValue1, "set multipart file value failed", errors.New("field cannot be set")) + return fault.WrapContext(contextOf(ctx), CodeSetMultipartFileValue1, "set multipart file value failed", errors.New("field cannot be set")) } switch fieldValue.Type() { case fileHeaderPointerType: @@ -352,7 +362,7 @@ func setMultipartFileValue(fieldValue reflect.Value, files []*multipart.FileHead fieldValue.Set(fileSlice) return nil } - return fault.Wrap(CodeSetMultipartFileValue2, "set multipart file value failed", fmt.Errorf("unsupported multipart file type %s", fieldValue.Type())) + return fault.WrapContext(contextOf(ctx), CodeSetMultipartFileValue2, "set multipart file value failed", fmt.Errorf("unsupported multipart file type %s", fieldValue.Type())) } // indirectKind 沿指针类型解析实际字段种类。 diff --git a/http/request/validation.go b/http/request/validation.go new file mode 100644 index 0000000..6a6cb70 --- /dev/null +++ b/http/request/validation.go @@ -0,0 +1,164 @@ +package request + +import ( + "context" + "errors" + "reflect" + "regexp" + "strings" + + failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "github.com/go-playground/validator/v10" +) + +var ( + namespaceIndices = regexp.MustCompile(`\[[^\]]*\]`) +) + +// FieldError 是允许公开的字段约束提示,不包含原始值或校验参数。 +type FieldError struct { + Field string `json:"field" dc:"声明中的公开字段路径,集合下标统一为 []"` + Rule string `json:"rule" dc:"服务端声明的校验规则名,不包含参数或输入值"` + Message string `json:"message" dc:"安全提示,可由字段静态 err 标签指定"` +} + +// ValidationDetails 是统一 400 响应中允许公开的字段错误数据。 +type ValidationDetails struct { + Fields []FieldError `json:"fields" dc:"按校验器顺序排列的安全字段错误"` +} + +// ValidationError 保留原生 validator 原因链及独立的公开提示。 +type ValidationError struct { + Fields []FieldError `json:"fields" dc:"不包含凭据或客户端值的字段级提示"` + cause error `dc:"已在可信调用上下文分类记录的原始错误链"` +} + +// Error 返回安全摘要。 +// 返回:固定的校验失败说明,不输出原始值或内部结构体命名。 +func (e *ValidationError) Error() string { return "request validation failed" } + +// Unwrap 保留 validator 的错误原因。 +// 返回:已记录的内部场景错误,支持继续 errors.As 到原生 ValidationErrors。 +func (e *ValidationError) Unwrap() error { return e.cause } + +// Code 返回所属校验失败场景码。 +// 返回:内部场景码,不作为公开业务错误码。 +func (e *ValidationError) Code() int { return CodeFormValidate1 } + +// validationResult 在校验源头分类并提取静态声明中的安全字段描述。 +// 入参:ctx 为标准上下文,receiver 为校验目标,err 为原生校验结果。 +// 返回:成功时为 nil,字段失败为 ValidationError,其他失败保留原始原因。 +func validationResult(ctx context.Context, receiver any, err error) error { + if err == nil { + return nil + } + classified := failure.WrapContext(ctx, CodeFormValidate1, "validate request fields failed", err) + var ( + fields validator.ValidationErrors + ) + if !errors.As(err, &fields) { + return classified + } + public := make([]FieldError, 0, len(fields)) + for _, field := range fields { + name, message := fieldDescription(reflect.TypeOf(receiver), field.StructNamespace()) + rule := field.Tag() + if message == "" { + message = validationMessage(rule) + } + public = append(public, FieldError{Field: name, Rule: rule, Message: message}) + } + return &ValidationError{Fields: public, cause: classified} +} + +// fieldDescription 只沿静态类型寻找公开名称,屏蔽动态 Map 键及集合下标。 +// 入参:root 为 Form 类型,namespace 为校验器返回的字段路径。 +// 返回:公开字段路径和字段 err 标签;无法映射或显式隐藏时使用 request 与通用提示。 +func fieldDescription(root reflect.Type, namespace string) (string, string) { + for root != nil && root.Kind() == reflect.Ptr { + root = root.Elem() + } + if root == nil || root.Kind() != reflect.Struct { + return "request", "" + } + namespace = strings.TrimPrefix(namespace, root.Name()+".") + parts := strings.Split(namespaceIndices.ReplaceAllString(namespace, "[]"), ".") + var ( + names []string + message string + ) + current := root + for _, part := range parts { + for current.Kind() == reflect.Ptr { + current = current.Elem() + } + if current.Kind() != reflect.Struct { + return "request", "" + } + identifier := strings.SplitN(part, "[", 2)[0] + field, ok := current.FieldByName(identifier) + if !ok || field.PkgPath != "" && !field.Anonymous { + return "request", "" + } + suffix := strings.TrimPrefix(part, identifier) + if strings.ReplaceAll(suffix, "[]", "") != "" { + return "request", "" + } + label := "" + for _, tag := range []string{"json", "form", "uri"} { + candidate := strings.SplitN(field.Tag.Get(tag), ",", 2)[0] + if candidate == "-" { + return "request", "" + } + if candidate != "" { + label = candidate + break + } + } + if label == "" && !field.Anonymous { + label = field.Name + } + if label != "" { + names = append(names, label+suffix) + } + current = field.Type + for i := 0; i < strings.Count(suffix, "[]"); i++ { + for current.Kind() == reflect.Ptr { + current = current.Elem() + } + switch current.Kind() { + case reflect.Map, reflect.Array, reflect.Slice: + current = current.Elem() + default: + return "request", "" + } + } + message = field.Tag.Get("err") + } + if len(names) == 0 { + return "request", "" + } + return strings.Join(names, "."), message +} + +// validationMessage 将常见规则转成不暴露输入或限制参数的安全说明。 +// 入参:rule 为服务端校验规则名。 +// 返回:英文缺省提示,自定义规则返回通用提示。 +func validationMessage(rule string) string { + switch rule { + case "required", "required_if", "required_with", "required_without": + return "This field is required" + case "email": + return "Invalid email address" + case "min", "gte", "gt": + return "Value is below the allowed minimum" + case "max", "lte", "lt": + return "Value exceeds the allowed maximum" + case "len": + return "Invalid length" + case "oneof": + return "Value is not allowed" + default: + return "Invalid value" + } +} diff --git a/http/response.go b/http/response.go index 0456495..80b17bc 100644 --- a/http/response.go +++ b/http/response.go @@ -9,6 +9,7 @@ import ( "git.zhangdeman.cn/github/ginframework/diagnostic" "git.zhangdeman.cn/github/ginframework/fault" + "git.zhangdeman.cn/github/ginframework/http/request" failure "git.zhangdeman.cn/github/ginframework/internal/failure" "git.zhangdeman.cn/github/ginframework/logger" "github.com/gin-gonic/gin" @@ -41,6 +42,11 @@ const ( codeTrustedType = 900424 codeRouteFrozen = 900425 codeRoutePath = 900426 + codeRequestBudget = 900427 + codeRequestTimeout = 900428 + codeHealthConfig = 900429 + codeReadinessCheck = 900430 + codeRequestCancelled = 900431 ) // PublicError 是业务显式允许公开的错误,不包含原始原因文本。 @@ -100,6 +106,13 @@ func (s *Server) writeResult(ctx *gin.Context, data any, err error, status int) } if status != 0 { public = &PublicError{Code: status, Message: http.StatusText(status), Status: status} + var ( + validation *request.ValidationError + ) + if status == http.StatusBadRequest && errors.As(err, &validation) { + public.Message = "Validation failed" + public.Data = request.ValidationDetails{Fields: validation.Fields} + } } result.Code, result.Message, result.Data = public.Code, public.Message, public.Data status = public.Status diff --git a/http/routes.go b/http/routes.go index a2234b2..0c64db0 100644 --- a/http/routes.go +++ b/http/routes.go @@ -84,7 +84,7 @@ func (s *Server) Group(prefix string, middleware []gin.HandlerFunc, controllers if meta.Tag.Get("path") == "" || meta.Tag.Get("method") == "" { return failure.Wrap(codeRouteDeclaration, "validate route declaration failed", errors.New("path and method tags are required")) } - for _, unsupported := range []string{"is-sse", "is-ws", "max-exec-time", "rate-limit", "hook-sync", "output_strict", "no-login"} { + for _, unsupported := range []string{"is-sse", "is-ws", "rate-limit", "hook-sync", "output_strict", "no-login"} { if raw := meta.Tag.Get(unsupported); raw != "" { return failure.Wrap(codeUnsupportedTag, "validate supported route tags failed", fmt.Errorf("tag %s requires an application adapter or a native route", unsupported)) } @@ -108,6 +108,14 @@ func (s *Server) Group(prefix string, middleware []gin.HandlerFunc, controllers // 入参:method 为注册期缓存的方法,formType 为 Form 类型,pointer 为参数形式,meta 为元数据字段。 // 返回:单路由 Handler 或声明错误。 func (s *Server) controllerHandler(method reflect.Value, formType reflect.Type, pointer bool, meta reflect.StructField) (gin.HandlerFunc, error) { + budget := time.Duration(*s.config.RequestTimeoutMS) * time.Millisecond + if raw := meta.Tag.Get("max-exec-time"); raw != "" { + seconds, err := strconv.ParseInt(raw, 10, 64) + if err != nil || seconds < 0 || seconds > int64((1<<63-1)/time.Second) { + return nil, failure.Wrap(codeRequestBudget, "validate route request budget failed", errors.New("invalid max-exec-time seconds")) + } + budget = time.Duration(seconds) * time.Second + } limit := request.DefaultMaxBodyBytes if raw := meta.Tag.Get("max-body-bytes"); raw != "" { parsed, err := strconv.ParseInt(raw, 10, 64) @@ -117,8 +125,19 @@ func (s *Server) controllerHandler(method reflect.Value, formType reflect.Type, limit = parsed } return func(ctx *gin.Context) { + if budget > 0 { + requestContext, cancel := context.WithTimeout(ctx.Request.Context(), budget) + defer cancel() + ctx.Request = ctx.Request.WithContext(requestContext) + } + if s.finishCanceled(ctx, nil) { + return + } form := reflect.New(formType) if err := request.Form.Bind(ctx, form.Interface(), request.WithMaxBodyBytes(limit)); err != nil { + if s.finishCanceled(ctx, err) { + return + } status := http.StatusBadRequest var ( large *http.MaxBytesError @@ -134,14 +153,23 @@ func (s *Server) controllerHandler(method reflect.Value, formType reflect.Type, } defaults.SetDefaults(form.Interface()) if err := s.inject(ctx, form.Elem()); err != nil { + if s.finishCanceled(ctx, err) { + return + } s.writeResult(ctx, nil, err, http.StatusInternalServerError) return } - if err := request.Form.Validate(form.Interface()); err != nil { + if err := request.Form.ValidateContext(ctx.Request.Context(), form.Interface()); err != nil { + if s.finishCanceled(ctx, err) { + return + } s.writeResult(ctx, nil, err, http.StatusBadRequest) return } input := form + if s.finishCanceled(ctx, nil) { + return + } if !pointer { input = form.Elem() } @@ -152,6 +180,9 @@ func (s *Server) controllerHandler(method reflect.Value, formType reflect.Type, if !isNil(result[1]) { err = result[1].Interface().(error) } + if s.finishCanceled(ctx, err) { + return + } s.writeResult(ctx, result[0].Interface(), err, 0) }, nil } @@ -181,7 +212,7 @@ func (s *Server) inject(ctx *gin.Context, form reflect.Value) error { if field.Kind() == reflect.Ptr { if field.IsNil() { if !field.CanSet() { - return failure.Wrap(codeInject, "resolve trusted field failed", errors.New("embedded field is not writable")) + return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", errors.New("embedded field is not writable")) } field.Set(reflect.New(field.Type().Elem())) } @@ -190,19 +221,19 @@ func (s *Server) inject(ctx *gin.Context, form reflect.Value) error { field = field.Field(index) } if !field.CanSet() { - return failure.Wrap(codeInject, "resolve trusted field failed", errors.New("trusted field is not writable")) + return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", errors.New("trusted field is not writable")) } field.SetZero() value, err := s.options.TrustedFields[name](ctx) if err != nil { - return failure.Wrap(codeTrustedRead, "read trusted field failed", err) + return failure.WrapContext(ctx.Request.Context(), codeTrustedRead, "read trusted field failed", err) } if value == nil { continue } source := reflect.ValueOf(value) if !source.Type().AssignableTo(field.Type()) { - return failure.Wrap(codeTrustedType, "assign trusted field failed", errors.New("trusted field type mismatch")) + return failure.WrapContext(ctx.Request.Context(), codeTrustedType, "assign trusted field failed", errors.New("trusted field type mismatch")) } field.Set(source) } diff --git a/http/server.go b/http/server.go index 6519640..6e1d73b 100644 --- a/http/server.go +++ b/http/server.go @@ -7,6 +7,7 @@ import ( "net/http" "sort" "sync" + "sync/atomic" "time" "git.zhangdeman.cn/github/ginframework/diagnostic" @@ -28,6 +29,7 @@ type Config struct { SuccessCode int `json:"success_code" yaml:"success_code" dc:"成功业务码,零为默认"` ReadHeaderTimeoutMS int `json:"read_header_timeout_ms" yaml:"read_header_timeout_ms" dc:"请求头读取超时毫秒,缺省 5000"` TrustedProxies []string `json:"trusted_proxies" yaml:"trusted_proxies" dc:"可信代理名单,缺省不信任转发头"` + RequestTimeoutMS *int64 `json:"request_timeout_ms" yaml:"request_timeout_ms" dc:"普通 Controller 请求合作式预算毫秒,缺省 30000,零禁用;原生 Handle 不自动套用"` } // Options 是调用方显式注入的 HTTP 运行依赖。 @@ -53,12 +55,21 @@ type Server struct { cancel context.CancelFunc `dc:"取消长请求及 SSE 的函数"` routes []route `dc:"启动期保存的不可变路由计划"` trustedFieldNames []string `dc:"启动时排序的可信字段名,避免每个请求重复构建和排序"` + ready atomic.Bool `dc:"应用装配完成的就绪信号,不代替依赖探测"` } // NewServer 创建独立 HTTP 实例,不修改 Gin 全局运行模式。 // 入参:cfg 为数据配置,options 为运行期函数及日志依赖。 // 返回:服务实例;非法代理和超时配置返回内部错误。 func NewServer(cfg Config, options Options) (*Server, error) { + budget := int64(30000) + if cfg.RequestTimeoutMS != nil { + budget = *cfg.RequestTimeoutMS + } + if budget < 0 || budget > int64((1<<63-1)/time.Millisecond) { + return nil, failure.Wrap(codeRequestBudget, "validate HTTP request budget failed", errors.New("invalid request budget")) + } + cfg.RequestTimeoutMS = &budget if cfg.ReadHeaderTimeoutMS < 0 { return nil, failure.Wrap(codeServerConfig, "validate HTTP timeout failed", errors.New("negative header timeout")) } @@ -154,6 +165,7 @@ func (s *Server) Serve(listener net.Listener) error { func (s *Server) Shutdown(ctx context.Context) error { s.lock.Lock() s.stopping = true + s.ready.Store(false) s.frozen = true server := s.server s.cancel() diff --git a/httpclient/request.go b/httpclient/request.go index 1d46650..712b3d5 100644 --- a/httpclient/request.go +++ b/httpclient/request.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "git.zhangdeman.cn/github/ginframework/diagnostic" failure "git.zhangdeman.cn/github/ginframework/internal/failure" ) @@ -28,10 +29,11 @@ type Request struct { // Response 保存有界缓冲结果,不对供应商业务码作推断。 type Response struct { - StatusCode int `json:"status_code" dc:"上游真实 HTTP 状态,非 2xx 也保留正文"` - Header http.Header `json:"-" dc:"上游原生响应头,不参与默认序列化"` - Body []byte `json:"-" dc:"完整响应字节,超限或读取失败时不返回部分正文"` - Duration time.Duration `json:"duration" dc:"从构造后发送到正文读取关闭完成的耗时,纳秒"` + diagnostics diagnostic.Snapshot `dc:"发送时的可信标量快照,不持有请求 Context 或可变对象"` + StatusCode int `json:"status_code" dc:"上游真实 HTTP 状态,非 2xx 也保留正文"` + Header http.Header `json:"-" dc:"上游原生响应头,不参与默认序列化"` + Body []byte `json:"-" dc:"完整响应字节,超限或读取失败时不返回部分正文"` + Duration time.Duration `json:"duration" dc:"从构造后发送到正文读取关闭完成的耗时,纳秒"` } // Build 创建原生请求,保留多值参数和正文类型,不执行网络请求。 @@ -144,17 +146,18 @@ func (c *Client) Send(ctx context.Context, input Request) (result *Response, err if int64(len(body)) > c.maxResponseBytes { return nil, failure.WrapContext(ctx, CodeResponseLimit, "buffer outbound response limit exceeded", ErrResponseTooLarge) } - return &Response{StatusCode: response.StatusCode, Header: response.Header.Clone(), Body: body}, nil + return &Response{StatusCode: response.StatusCode, Header: response.Header.Clone(), Body: body, diagnostics: diagnostic.From(ctx)}, nil } // DecodeJSON 解码单份响应 JSON,保留动态数字精度,不把解析失败当作空数据。 // 入参:target 为 encoding/json 支持的非空接收指针。 // 返回:目标类型不匹配、无效 JSON 或多份 JSON 返回内部错误,原始正文不进入日志。 func (r *Response) DecodeJSON(target any) error { + ctx := diagnostic.With(context.Background(), r.diagnostics) decoder := json.NewDecoder(bytes.NewReader(r.Body)) decoder.UseNumber() if err := decoder.Decode(target); err != nil { - return failure.Wrap(CodeJSONDecode, "decode outbound JSON response failed", err) + return failure.WrapContext(ctx, CodeJSONDecode, "decode outbound JSON response failed", err) } var ( extra any @@ -163,7 +166,7 @@ func (r *Response) DecodeJSON(target any) error { if err == nil { err = errors.New("multiple JSON values in response") } - return failure.Wrap(CodeJSONDocuments, "validate outbound JSON document count failed", err) + return failure.WrapContext(ctx, CodeJSONDocuments, "validate outbound JSON document count failed", err) } return nil } diff --git a/internal/failure/error.go b/internal/failure/error.go index 8502733..10db4e5 100644 --- a/internal/failure/error.go +++ b/internal/failure/error.go @@ -34,3 +34,11 @@ func Capture(target *error, code int, message string) { *target = Wrap(code, message, *target) } } + +// CaptureContext 为命名返回值补充场景并在原调用上下文记录一次。 +// 入参:ctx 为可信标准上下文,target 为命名返回值地址,code 为场景码,message 为安全摘要。 +func CaptureContext(ctx context.Context, target *error, code int, message string) { + if target != nil { + *target = WrapContext(ctx, code, message, *target) + } +} diff --git a/redis/client.go b/redis/client.go index 4c2c7fa..0afcf37 100644 --- a/redis/client.go +++ b/redis/client.go @@ -51,7 +51,7 @@ func Open(ctx context.Context, cfg Config, instance *zap.Logger) (*redisclient.C ctx = context.Background() } if cfg.Address == "" || cfg.DB < 0 || cfg.ProbeTimeoutMS < 0 || cfg.PoolSize < 0 || cfg.MinIdleConns < 0 || cfg.MaxIdleConns < 0 || cfg.MaxActiveConns < 0 || cfg.PoolTimeoutMS < 0 || cfg.ConnMaxIdleTimeMS < 0 || cfg.ConnMaxLifetimeMS < 0 || (cfg.Network != "" && cfg.Network != "tcp" && cfg.Network != "unix") { - return nil, fault.Wrap(CodeConfig, "validate Redis configuration failed", errors.New("invalid Redis target or pool configuration")) + return nil, fault.WrapContext(ctx, CodeConfig, "validate Redis configuration failed", errors.New("invalid Redis target or pool configuration")) } options := &redisclient.Options{ Addr: cfg.Address, Network: cfg.Network, Username: cfg.Username, Password: cfg.Password, DB: cfg.DB, ClientName: cfg.Name, @@ -81,7 +81,7 @@ func Open(ctx context.Context, cfg Config, instance *zap.Logger) (*redisclient.C probe, cancel := context.WithTimeout(ctx, time.Duration(cfg.ProbeTimeoutMS)*time.Millisecond) defer cancel() if err := client.Ping(probe).Err(); err != nil { - return nil, errors.Join(fault.Wrap(CodeProbe, "probe Redis failed", err), fault.Wrap(CodeClose, "close pending Redis client failed", client.Close())) + return nil, errors.Join(fault.WrapContext(ctx, CodeProbe, "probe Redis failed", err), fault.WrapContext(ctx, CodeClose, "close pending Redis client failed", client.Close())) } return client, nil }