抽取 Gin、配置、日志、数据库、Redis 与出站 HTTP 基础能力。 新增统一接入指南,将能力清单和相对链接检查纳入 make verify。 对齐远端 module 路径,修正 Redis 读写超时特殊值映射。 验证:make verify、make race-check 均通过。
This commit is contained in:
commit
b4c3ac622c
55 files changed
+5862
No files matched your search
@@ -0,0 +1,97 @@
|
||||
// Package redis 创建原生 Redis 客户端,实例用途和所有权由应用确定。
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
fault "git.zhangdeman.cn/github/ginframework/internal/failure"
|
||||
"git.zhangdeman.cn/github/ginframework/redis/commandlog"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
// CodeConfig 表示 Redis 连接配置无效。
|
||||
CodeConfig = 900301
|
||||
// CodeProbe 表示 Redis 启动探测失败。
|
||||
CodeProbe = 900302
|
||||
// CodeClose 表示启动失败后的 Redis 连接回收失败。
|
||||
CodeClose = 900303
|
||||
)
|
||||
|
||||
// Config 描述 Redis 连接,超时和重试使用指针保留客户端的特殊值。
|
||||
type Config struct {
|
||||
Name string `json:"name" yaml:"name" dc:"应用定义的实例名"`
|
||||
Address string `json:"address" yaml:"address" dc:"TCP host:port 或 Unix socket 路径"`
|
||||
Network string `json:"network" yaml:"network" dc:"连接网络,缺省 tcp,可选 unix"`
|
||||
Username string `json:"username" yaml:"username" dc:"ACL 用户名"`
|
||||
Password string `json:"password" yaml:"password" dc:"部署注入的密码"`
|
||||
DB int `json:"db" yaml:"db" dc:"数据库索引"`
|
||||
MaxRetries *int `json:"max_retries" yaml:"max_retries" dc:"缺省使用客户端默认重试,-1 禁止重试"`
|
||||
DialTimeoutMS *int `json:"dial_timeout_ms" yaml:"dial_timeout_ms" dc:"连接超时毫秒,缺省使用客户端默认值"`
|
||||
ReadTimeoutMS *int `json:"read_timeout_ms" yaml:"read_timeout_ms" dc:"读取超时毫秒,保留客户端负值语义"`
|
||||
WriteTimeoutMS *int `json:"write_timeout_ms" yaml:"write_timeout_ms" dc:"写入超时毫秒,保留客户端负值语义"`
|
||||
PoolSize int `json:"pool_size" yaml:"pool_size" dc:"连接池大小,零使用客户端默认值"`
|
||||
PoolTimeoutMS int `json:"pool_timeout_ms" yaml:"pool_timeout_ms" dc:"等待连接超时毫秒,零使用客户端默认值"`
|
||||
MinIdleConns int `json:"min_idle_conns" yaml:"min_idle_conns" dc:"最小空闲连接数"`
|
||||
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns" dc:"最大空闲连接数,零不限制"`
|
||||
MaxActiveConns int `json:"max_active_conns" yaml:"max_active_conns" dc:"最大活动连接数,零不限制"`
|
||||
ConnMaxIdleTimeMS int `json:"conn_max_idle_time_ms" yaml:"conn_max_idle_time_ms" dc:"空闲连接寿命毫秒,零使用客户端默认值"`
|
||||
ConnMaxLifetimeMS int `json:"conn_max_lifetime_ms" yaml:"conn_max_lifetime_ms" dc:"连接寿命毫秒,零表示不限制"`
|
||||
ProbeTimeoutMS int `json:"probe_timeout_ms" yaml:"probe_timeout_ms" dc:"启动探测超时毫秒,缺省 5000"`
|
||||
}
|
||||
|
||||
// Open 创建、安装观测钩子并探测 Redis,返回原生客户端。
|
||||
// 入参:ctx 为启动上下文,cfg 为数据配置,instance 为可选已有日志。
|
||||
// 返回:由应用关闭的客户端;失败关闭临时客户端并保留错误链。
|
||||
func Open(ctx context.Context, cfg Config, instance *zap.Logger) (*redisclient.Client, error) {
|
||||
if ctx == nil {
|
||||
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"))
|
||||
}
|
||||
options := &redisclient.Options{
|
||||
Addr: cfg.Address, Network: cfg.Network, Username: cfg.Username, Password: cfg.Password, DB: cfg.DB, ClientName: cfg.Name,
|
||||
PoolSize: cfg.PoolSize, MinIdleConns: cfg.MinIdleConns, MaxIdleConns: cfg.MaxIdleConns, MaxActiveConns: cfg.MaxActiveConns,
|
||||
PoolTimeout: time.Duration(cfg.PoolTimeoutMS) * time.Millisecond, ConnMaxIdleTime: time.Duration(cfg.ConnMaxIdleTimeMS) * time.Millisecond, ConnMaxLifetime: time.Duration(cfg.ConnMaxLifetimeMS) * time.Millisecond,
|
||||
ContextTimeoutEnabled: true,
|
||||
}
|
||||
if cfg.MaxRetries != nil {
|
||||
options.MaxRetries = *cfg.MaxRetries
|
||||
}
|
||||
if cfg.DialTimeoutMS != nil {
|
||||
options.DialTimeout = time.Duration(*cfg.DialTimeoutMS) * time.Millisecond
|
||||
}
|
||||
if cfg.ReadTimeoutMS != nil {
|
||||
options.ReadTimeout = commandTimeout(*cfg.ReadTimeoutMS)
|
||||
}
|
||||
if cfg.WriteTimeoutMS != nil {
|
||||
options.WriteTimeout = commandTimeout(*cfg.WriteTimeoutMS)
|
||||
}
|
||||
client := redisclient.NewClient(options)
|
||||
if instance != nil {
|
||||
client.AddHook(commandlog.New(instance, cfg.Name))
|
||||
}
|
||||
if cfg.ProbeTimeoutMS == 0 {
|
||||
cfg.ProbeTimeoutMS = 5000
|
||||
}
|
||||
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 client, nil
|
||||
}
|
||||
|
||||
// commandTimeout 将读写配置转为客户端时长,保留原生的特殊控制值。
|
||||
// 入参:milliseconds 为毫秒数;-1/-2 是 go-redis 的原生哨兵,不是负毫秒。
|
||||
// 返回:普通时长按毫秒换算,两个特殊值保持原生 time.Duration 数值。
|
||||
func commandTimeout(milliseconds int) time.Duration {
|
||||
if milliseconds == -1 || milliseconds == -2 {
|
||||
return time.Duration(milliseconds)
|
||||
}
|
||||
return time.Duration(milliseconds) * time.Millisecond
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zhangdeman.cn/github/ginframework/fault"
|
||||
"git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver"
|
||||
)
|
||||
|
||||
func TestOpenNativeClientAndProbeFailure(t *testing.T) {
|
||||
native := redisserver.New(t, 3)
|
||||
disableRetries := -1
|
||||
client, err := Open(context.Background(), Config{Name: "test", Network: "unix", Address: native.Options().Addr, MaxRetries: &disableRetries}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := client.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if err := client.Set(context.Background(), "example", "kept", 0).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value, err := client.Get(context.Background(), "example").Result(); err != nil || value != "kept" {
|
||||
t.Fatalf("native result changed: %q %v", value, err)
|
||||
}
|
||||
missing, err := Open(context.Background(), Config{Network: "unix", Address: filepath.Join(t.TempDir(), "missing.sock"), MaxRetries: &disableRetries, ProbeTimeoutMS: 50}, nil)
|
||||
if missing != nil || !fault.Internal(err) {
|
||||
t.Fatal("failed probe published a client")
|
||||
}
|
||||
cancelled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
missing, err = Open(cancelled, Config{Network: "unix", Address: native.Options().Addr, MaxRetries: &disableRetries}, nil)
|
||||
if missing != nil || !errors.Is(err, context.Canceled) {
|
||||
t.Fatal("startup cancellation lost")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadWriteTimeoutSentinelsKeepNativeSemantics(t *testing.T) {
|
||||
native := redisserver.New(t, 3)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
value int
|
||||
expected time.Duration
|
||||
}{
|
||||
{name: "no timeout", value: -1, expected: 0},
|
||||
{name: "skip deadline", value: -2, expected: -1},
|
||||
{name: "milliseconds", value: 120, expected: 120 * time.Millisecond},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
client, err := Open(context.Background(), Config{
|
||||
Network: "unix",
|
||||
Address: native.Options().Addr,
|
||||
ReadTimeoutMS: &test.value,
|
||||
WriteTimeoutMS: &test.value,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := client.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
options := client.Options()
|
||||
if options.ReadTimeout != test.expected || options.WriteTimeout != test.expected {
|
||||
t.Fatalf("native timeout semantics lost: read=%v write=%v", options.ReadTimeout, options.WriteTimeout)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// Package redislog 通过 go-redis 官方 Hook 记录完整执行流水及 Pipeline 逐条结果。
|
||||
package commandlog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.zhangdeman.cn/github/ginframework/logger/storagevalue"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Hook 只持有入口日志实例和逻辑 Redis 实例标识。
|
||||
type Hook struct {
|
||||
logger *zap.Logger `dc:"已初始化的执行日志实例"`
|
||||
instance string `dc:"固定 Redis 实例标识"`
|
||||
}
|
||||
|
||||
var (
|
||||
_ redis.Hook = (*Hook)(nil)
|
||||
)
|
||||
|
||||
// New 创建不改变执行语义的观测钩子。
|
||||
// 入参:logger 为已有日志单例,instance 为 Redis 实例名。
|
||||
// 返回:原生客户端可直接安装的 Hook。
|
||||
func New(logger *zap.Logger, instance string) redis.Hook {
|
||||
return &Hook{
|
||||
logger: logger,
|
||||
instance: instance,
|
||||
}
|
||||
}
|
||||
|
||||
// DialHook 复用原始拨号,不接管连接、超时或重试。
|
||||
// 入参:next 为原生拨号函数。
|
||||
// 返回:原函数。
|
||||
func (h *Hook) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
// ProcessHook 记录一次命令执行结果,原样返回底层错误。
|
||||
// 入参:next 为原生处理函数。
|
||||
// 返回:仅附加执行观测的处理函数。
|
||||
func (h *Hook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
var (
|
||||
begin = time.Now()
|
||||
)
|
||||
var (
|
||||
err = next(ctx, cmd)
|
||||
)
|
||||
h.record(ctx, cmd, time.Since(begin), err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// ProcessPipelineHook 逐条记录流水,保留 Pipeline 的命令与结果对应关系。
|
||||
// 入参:next 为原生 Pipeline 处理函数。
|
||||
// 返回:保留原执行错误的 Pipeline 处理函数。
|
||||
func (h *Hook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(ctx context.Context, cmds []redis.Cmder) error {
|
||||
var (
|
||||
begin = time.Now()
|
||||
)
|
||||
var (
|
||||
err = next(ctx, cmds)
|
||||
)
|
||||
var (
|
||||
elapsed = time.Since(begin)
|
||||
)
|
||||
for _, cmd := range cmds {
|
||||
h.record(ctx, cmd, elapsed, cmd.Err())
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// record 生成日志副本,认证管理命令及敏感键隐藏整组参数和结果。
|
||||
// 入参:ctx 为可信诊断上下文,cmd 为原生命令,elapsed 为执行耗时,resultErr 为当前命令真实结果。
|
||||
func (h *Hook) record(ctx context.Context, cmd redis.Cmder, elapsed time.Duration, resultErr error) {
|
||||
var (
|
||||
args = cmd.Args()
|
||||
)
|
||||
var (
|
||||
result any
|
||||
)
|
||||
var (
|
||||
loggedArgs any
|
||||
)
|
||||
var (
|
||||
hidden bool
|
||||
)
|
||||
var (
|
||||
status = "success"
|
||||
)
|
||||
var (
|
||||
name = strings.ToLower(cmd.Name())
|
||||
)
|
||||
var (
|
||||
method reflect.Value
|
||||
)
|
||||
var (
|
||||
values []reflect.Value
|
||||
)
|
||||
var (
|
||||
fields []zap.Field
|
||||
)
|
||||
if h.logger == nil {
|
||||
return
|
||||
}
|
||||
hidden = name == "auth" || name == "hello" || name == "acl" || name == "config" || name == "migrate" || name == "restore"
|
||||
for _, arg := range args {
|
||||
if value, ok := arg.(string); ok && storagevalue.Sensitive(value) {
|
||||
hidden = true
|
||||
}
|
||||
}
|
||||
if hidden {
|
||||
loggedArgs = "[REDACTED]"
|
||||
result = "[REDACTED]"
|
||||
} else {
|
||||
loggedArgs = storagevalue.Safe(args)
|
||||
method = reflect.ValueOf(cmd).MethodByName("Val")
|
||||
if method.IsValid() && method.Type().NumIn() == 0 && method.Type().NumOut() == 1 {
|
||||
values = method.Call(nil)
|
||||
result = storagevalue.Safe(values[0].Interface())
|
||||
}
|
||||
}
|
||||
// 单命令的 SetErr 在官方 ProcessHook 返回后才执行,不能在钩子中仅依赖 cmd.Err。
|
||||
if errors.Is(resultErr, redis.Nil) {
|
||||
status = "miss"
|
||||
} else if resultErr != nil {
|
||||
status = "failed"
|
||||
}
|
||||
fields = []zap.Field{zap.String("instance", h.instance), zap.String("command", name), zap.Duration("duration", elapsed), zap.String("result", status), zap.Any("args", loggedArgs), zap.Any("value", result)}
|
||||
fields = append(fields, storagevalue.Diagnostics(ctx)...)
|
||||
h.logger.Info("Redis command execution completed", fields...)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package commandlog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zaptest/observer"
|
||||
)
|
||||
|
||||
// TestNativePipelineObservationPreservesData 验证 Pipeline 逐条对应记录,日志脱敏不修改执行参数和返回正文。
|
||||
func TestNativePipelineObservationPreservesData(t *testing.T) {
|
||||
var (
|
||||
client = redisserver.New(t, 3)
|
||||
)
|
||||
var (
|
||||
core, logs = observer.New(zap.InfoLevel)
|
||||
)
|
||||
var (
|
||||
ctx = context.Background()
|
||||
)
|
||||
var (
|
||||
value = `{"nested":{"token":"private-token"},"data":"kept"}`
|
||||
)
|
||||
client.AddHook(New(zap.New(core), "cache"))
|
||||
var (
|
||||
pipeline = client.Pipeline()
|
||||
)
|
||||
pipeline.Set(ctx, "safe-key", value, 0)
|
||||
var (
|
||||
get = pipeline.Get(ctx, "safe-key")
|
||||
)
|
||||
var (
|
||||
missing = pipeline.Get(ctx, "missing-key")
|
||||
)
|
||||
if _, err := pipeline.Exec(ctx); !errors.Is(err, redis.Nil) {
|
||||
t.Fatalf("pipeline error changed: %v", err)
|
||||
}
|
||||
if get.Val() != value || !errors.Is(missing.Err(), redis.Nil) {
|
||||
t.Fatal("logging changed actual command result")
|
||||
}
|
||||
var (
|
||||
commands []observer.LoggedEntry
|
||||
)
|
||||
for _, entry := range logs.All() {
|
||||
if name := entry.ContextMap()["command"]; name == "set" || name == "get" {
|
||||
commands = append(commands, entry)
|
||||
}
|
||||
}
|
||||
if len(commands) != 3 {
|
||||
t.Fatalf("pipeline records=%d, want 3", len(commands))
|
||||
}
|
||||
for _, entry := range logs.All() {
|
||||
body, _ := json.Marshal(entry.ContextMap())
|
||||
if strings.Contains(string(body), "private-token") {
|
||||
t.Fatal("credential leaked into execution log")
|
||||
}
|
||||
}
|
||||
if commands[2].ContextMap()["result"] != "miss" {
|
||||
t.Fatal("Redis nil observation changed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHookObservesReturnedError 验证官方回调返回前尚未 SetErr 时不会误记成功。
|
||||
func TestHookObservesReturnedError(t *testing.T) {
|
||||
var (
|
||||
core, logs = observer.New(zap.InfoLevel)
|
||||
)
|
||||
var (
|
||||
hook = New(zap.New(core), "cache")
|
||||
)
|
||||
var (
|
||||
cmd = redis.NewStringCmd(context.Background(), "get", "safe-key")
|
||||
)
|
||||
var (
|
||||
calls int
|
||||
)
|
||||
var (
|
||||
process = hook.ProcessHook(func(context.Context, redis.Cmder) error { calls++; return context.Canceled })
|
||||
)
|
||||
if err := process(context.Background(), cmd); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("error changed: %v", err)
|
||||
}
|
||||
if calls != 1 || cmd.Err() != nil || logs.Len() != 1 || logs.All()[0].ContextMap()["result"] != "failed" {
|
||||
t.Fatalf("hook altered command or observed wrong result: %v", logs.All())
|
||||
}
|
||||
}
|
||||