100 Commits

Author SHA1 Message Date
xfy
e5885ce888 fix(proxy): correct response time recording for Least Time
- Record headerTime when header is received
- Record lastByteTime when response is complete
- Use correct timing calculations (headerReceived/connectEnd/responseEnd)
2026-06-08 18:17:08 +08:00
xfy
72f189bba8 feat(proxy): integrate Least Time and Sticky balancers
- Add least_time and sticky to createBalancerByName
- Implement response time recording for Least Time
- Support StickySession in target selector with request context
- StickySession auto-starts when created
2026-06-08 18:11:47 +08:00
xfy
0a53622351 perf(proxy): pre-build cacheIgnoreSet, single-pass cache key, pool UpstreamTiming
Three optimizations in the proxy cache hot path:

- Pre-build cacheIgnoreSet map once at Proxy creation instead of
  per-response. Eliminates map allocation + linear scan per cached
  response.

- Compute cache key once per request via computeCacheKey() closure.
  Previously buildCacheKeyHash was called up to 5 times per request;
  now computed on first access and reused.

- Pool UpstreamTiming objects with sync.Pool. Eliminates one heap
  allocation per proxied request.
2026-06-04 10:57:38 +08:00
xfy
02775de641 perf(proxy): eliminate string allocations in isWebSocketRequest
Replace string(connection)/strings.EqualFold/strings.ToLower with
bytes.EqualFold and utils.BytesContainsFold. Removes 2-4 heap
allocations per proxied request.
2026-06-04 10:48:57 +08:00
xfy
83d4e5e860 perf(proxy): inline FNV-1a in buildCacheKeyHash/buildCacheKeyHashValue
Replaces fnv.New64a() with direct inline hash computation over
fasthttp's []byte slices, eliminating 1 allocation per cache key
computation and 1 []byte(":") allocation.
2026-06-04 10:45:55 +08:00
xfy
164589a9cc test(proxy): 添加代理模块低覆盖率函数测试(覆盖率 71.1% → 预计 >80%)
新建 internal/proxy/proxy_low_coverage_test.go,覆盖:

proxyDebugLog 测试(原 0%):
- 字符串/整数/布尔/错误/nil 值的调试日志
- 空键值对处理

ServeHTTP 测试(原 47.3%):
- GET/POST/PUT 真实后端转发
- 连接拒绝、超时、故障转移
- X-Accel-Redirect 内部重定向
- 可疑路径拦截
- 缓存存储/命中/stale
- 重定向重写、空 URL、查询参数

selectTarget 测试(原 46.7%):
- random 算法选择
- Lua 选择成功/回退

selectByLua 测试(原 39.1%):
- 有效脚本执行、未选择、无 ngx 表

backgroundRefresh 测试(原 41.9%):
- 缓存条目重新验证、请求错误

WebSocket 测试(原 15.4%):
- Hijack 失败、读取响应、升级拒绝
- 拨号目标成功/超时

DNS 解析测试(原 0%):
- Start 幂等性、解析器启动失败
- 刷新成功/错误、TTL 获取
- 默认端口处理

WebSocket 辅助函数测试:
- 头部配置、升级响应错误、连接关闭错误
2026-06-04 08:33:29 +08:00
xfy
6612819f3a chore: remove stale AGENTS.md files, rewrite root AGENTS.md 2026-06-03 23:47:29 +08:00
xfy
29752f62bd fix: resolve golangci-lint issues across multiple packages
- stream: fix atomic.Int64 usage in tests and benchmarks
- server: fix errcheck, goconst ("tcp" -> constant), and govet shadow
- app: add missing ServerModeAuto case in requiresFullRestart
- lua: fix nolintlint unused directive warnings
- proxy: use `any` instead of `interface{}`
2026-06-03 18:17:07 +08:00
xfy
6f17bbad7e chore: remove trailing blank lines and clean up whitespace 2026-06-03 18:08:34 +08:00
xfy
ae3c167cd6 refactor: remove extractHostFromURL, use netutil.ParseTargetURL 2026-06-03 17:50:06 +08:00
xfy
041bc97578 refactor: remove unused code identified by staticcheck 2026-06-03 17:46:58 +08:00
xfy
1a6b5f9166 Merge origin/master into master 2026-06-03 16:36:23 +08:00
xfy
2734b04d8f refactor: remove 16.8k lines of dead code across all internal packages
- Delete unused files: tempfile subsystem, matcher variants, server/internal
- Remove 200+ unused functions across proxy, ssl, lua, http2/3, stream, variable
- Fix proxy test type errors (backgroundRefresh ctx→Request)
- Move bench/tools mock backend into internal/testutil
- Remove corresponding test functions for all deleted code
2026-06-03 16:15:43 +08:00
5dec128510
Merge pull request #3 from xfy911/improve-comments
docs: add comprehensive documentation comments
2026-06-03 15:41:36 +08:00
xfy911
dc54d3822f docs(proxy): add package comments for proxy module
- Add package documentation for target_selector, utils, validate,
  cache_handler, and header_modifier files
- Include author attribution (xfy)
2026-06-03 15:28:53 +08:00
xfy
8ae4add922 fix: address code review feedback
- proxyDebugLog: move Enabled() guard to call sites to avoid allocations
- proxyDebugLog: add default case for unsupported types
- static routes: remove unintended regex support to match original behavior
2026-06-03 14:29:30 +08:00
xfy
8681472c4b refactor: use testutil helpers in proxy tests 2026-06-03 14:10:07 +08:00
xfy
1ce42c039b refactor: extract proxyDebugLog helper for repeated debug logging 2026-06-03 13:57:55 +08:00
xfy
f6c1ee8180 fix(proxy): log error when upstream TLS config creation fails
Previously the error was silently swallowed, causing the proxy to
fall back to default TLS settings (no custom CA, no mTLS, no SNI)
without any indication. Now the error is logged at ERROR level.
2026-06-03 01:09:40 +08:00
xfy
2c3cc1ba38 fix(proxy): prevent use-after-recycle in background cache refresh
Copy the request before spawning the background goroutine. The
fasthttp.RequestCtx is recycled after the handler returns, so passing
it to a goroutine causes data corruption under high concurrency.

The caller now AcquireRequest+CopyTo before go(), and the goroutine
releases it. backgroundRefresh no longer accepts ctx directly.
2026-06-03 01:08:50 +08:00
xfy
a28c7ebcf1 refactor(utils): add unified b2s/s2b conversion functions
Extract duplicate b2s/s2b functions from proxy/utils.go into
internal/utils/bytes.go. These are zero-allocation unsafe conversions
for byte slice <-> string conversion.

- Create utils.B2s() and utils.S2b() as unified implementations
- Update proxy/utils.go to call utils functions
- Add safety documentation about shared memory warning

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 18:06:25 +08:00
xfy
144e101c09 feat(proxy): add configurable X-Forwarded-Host and X-Forwarded-Proto headers
Add `set_forwarded_host` and `set_forwarded_proto` options to control
whether the proxy automatically sets these headers. This fixes issues
with upstream servers that validate X-Forwarded-Host against known hosts.

Changes:
- Add SetForwardedHost/SetForwardedProto fields to ProxyHeaders struct
- Modify SetForwardedHeaders and WriteForwardedHeaders function signatures
- Update modifyRequestHeaders to read config and pass control parameters
- Update WebSocket call chain to support new config
- Add unit tests for new functionality
- Update default config generation (-g) to include new options

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 13:28:28 +08:00
xfy
d269940d8b style: fix formatting issues
- Add missing newlines at end of files
- Fix indentation in ssl.go
- Remove extra blank lines

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-30 13:42:53 +08:00
xfy
b1e1547e36 fix(lint): resolve errcheck and goconst issues
- Add nolint comments for sync.Pool.Get() type assertions (pool always returns valid pointers)
- Extract TLS version strings to constants in sslutil/tlsconfig.go
- Extract expires directive strings to constants in handler/static.go

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-30 13:41:15 +08:00
xfy
f145a8770e refactor: modernize code with Go 1.22+ features
Apply modern Go patterns across the codebase:
- Replace `interface{}` with `any` (Go 1.18+)
- Use `for range n` instead of `for i := 0; i < n; i++` (Go 1.22+)
- Replace `sort.Slice` with `slices.Sort` from slices package
- Simplify sync.WaitGroup patterns with errgroup where appropriate
- Add Makefile targets for modernize analyzer

Total: 84 files updated, net reduction of 79 lines

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-30 10:37:45 +08:00
xfy
6b8b00c900 refactor(ssl): extract TLS config generation to sslutil
- 新增 internal/sslutil/tlsconfig.go 统一 TLS 配置函数
- 提取 ParseTLSVersion/ParseCipherSuites/DefaultCipherSuites 等
- 更新 ssl.go/stream/ssl.go/proxy_ssl.go 使用统一函数
- 消除约 150 行重复代码

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 18:18:33 +08:00
xfy
ade4f84d1f test(proxy): 连接池满载场景测试
测试连接池不同负载场景:
- Normal: 92 allocs/op (正常并发)
- HighConcurrency: 155 allocs/op (高并发)
- MultiTarget: 104 allocs/op (多目标连接池)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 10:50:08 +08:00
xfy
0d987bb060 test(proxy): 缓存键零分配验证测试
验证 buildCacheKeyHashValue 零分配优化:
- ZeroAlloc: 0 allocs/op (已达标)
- WithAlloc: 1 allocs/op (对比基准)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 10:39:06 +08:00
xfy
11e22c80b8 perf: 零分配优化与 Dial timeout 支持
- 添加 b2s/s2b 零分配字节-字符串转换工具函数
- WebSocket 数据转发使用 sync.Pool 复用 32KB buffer
- 条件化 Debug 日志避免非 Debug 级别的字符串分配
- 缓存键哈希计算直接写入 []byte 避免 string 转换
- 使用 bytes.EqualFold 替代 strings.ToLower 进行大小写不敏感比较
- generateETag 使用 strconv.AppendInt 避免 fmt.Sprintf
- 支持 Dial timeout 配置,区分 TCP 连接建立和总连接超时
- MaxConnsPerHost 默认值改为 512(fasthttp 推荐)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-28 20:11:20 +08:00
xfy
cf2fcca7e8 refactor: 提取公共逻辑、消除重复代码、加强错误处理
- 提取 App 公共逻辑到 app_common.go,消除 app.go/app_windows.go 重复定义
- 提取 Server 生命周期/中间件/路由逻辑到独立文件(lifecycle.go/middleware_builder.go/router.go)
- 提取 Proxy 缓存处理/头部修改/目标选择到独立模块
- 提取 CheckIPAccess/CheckTokenAuth 到 utils/httperror.go,消除 status/purge 重复实现
- 修复 stream 双向转发:任一方向完成立即关闭双端,避免连接泄漏
- 修复 SSL/TLS 中静默忽略错误的问题,添加日志记录
- 统一日志消息为英文

💘 Generated with Crush

Assisted-by: GLM 5.1 via Crush <crush@charm.land>
2026-04-28 18:00:48 +08:00
xfy
179090fa34 fix(security): 修复 2 个 CRITICAL + 6 个 HIGH 安全与代码质量问题
安全修复:
- ConnLimiter Acquire() TOCTOU 竞态: atomic.AddInt64 替代 loadInt64+addInt64
- Cache Purge token 时序侧信道: 改用 subtle.ConstantTimeCompare
- Lua Cosocket SSRF: 新增 ip_guard 两层 IP 检查(字面量+解析后),拒绝私有/回环地址
- X-Accel-Redirect 路径遍历: urlpath.Clean + 前缀拒绝(/internal/ /admin/)
- CRLF 注入: containsCRLF 校验变量展开后的 header 值,logging.Warn 可观测
- Proxy URI 注入: bytes.ContainsAny 检查 path 中的 @\r\n 危险字符

代码质量:
- disk_cache.go Set() 7 处静默 return 改为 logging.Error 日志记录
- config.go 从 2392 行拆分为 9 个按域文件(config/server/proxy/security/ssl/cache/performance/monitoring/variable)

验证: go build + vet + golangci-lint(0 issues) + test(83.2% 无回归) + race detector 全部通过

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-28 10:13:47 +08:00
xfy
be974b2e18 feat(proxy,config): 代理层集成 stale 缓存回退逻辑
上游请求失败时,根据错误类型(超时/其他)调用 GetStale 尝试返回
过期缓存。配置文件示例补充 stale_if_error 和 stale_if_timeout 字段。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 10:06:27 +08:00
xfy
8f79fb6797 test(config,handler,loadbalance,proxy): 扩展单元测试覆盖率
添加以下测试:
- validate_test.go: Rewrite、NextUpstream、DefaultServer、Mode、
  ListenConflicts、HTTP2、RedirectRewrite 验证测试
- sendfile_test.go: 无效文件描述符、零长度传输、部分传输、
  带偏移量传输测试
- balancer_test.go: ConsistentHash Select/SelectExcluding、
  RandomBalancer 边界条件和 Power of Two Choices 测试
- health_test.go: MarkHealthy/MarkUnhealthy 与 SlowStartManager
  集成测试

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 18:28:28 +08:00
xfy
00c5319819 refactor(proxy,server): 改进健康检查 goroutine 退出机制
- health: 使用 WaitGroup 确保 run goroutine 完全退出后再继续
- health_match: 忽略未使用参数,预分配 slice 容量
- proxy_coverage_extra_test: 使用 atomic.Int32 修复测试竞态条件
- purge: 忽略 Delete 返回值

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 13:35:03 +08:00
xfy
92b7040a5f feat(proxy,config): 增强健康检查和缓存配置
健康检查增强:
- 添加 HealthMatch 接口支持自定义健康判断逻辑
- 支持状态码范围、响应体正则、响应头匹配
- 集成 SlowStartManager 实现慢启动

配置增强:
- HealthCheckConfig 新增 Match 和 SlowStart 字段
- ProxyBufferingConfig 支持 Buffers 配置字符串格式
- 新增 ProxyCachePathConfig 磁盘缓存路径配置
- 添加 StaleIfError/StaleIfTimeout 缓存配置

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 13:15:18 +08:00
xfy
9f7090df67 test(handler,middleware,server,ssl,proxy): 扩展测试覆盖率
- handler: 添加 sendfile 和 static 处理器测试
- middleware/security: 添加访问控制、认证、请求头、限流测试
- server: 添加池、pprof、清理、状态、升级、vhost 测试
- ssl: 添加客户端验证、OCSP、SSL 测试
- proxy: 添加代理覆盖率补充测试

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 10:42:05 +08:00
xfy
4697f39924 refactor(proxy): 消除缓存处理中的 goto 语句
重构 ServeHTTP 中的缓存逻辑,用嵌套 if 结构替代 goto proxyRequest,
使控制流更清晰。主要变更:
- 缓存命中逻辑内聚到 rule != nil 分支
- 缓存锁等待后重新检查缓存命中
- 移除 proxyRequest 标签

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 08:08:44 +08:00
xfy
0a7f7170d5 feat(cache,proxy): 增强代理缓存功能
- 添加 min_uses 阈值支持,请求次数达标才缓存
- 添加 cache_lock_timeout 配置,防止缓存锁无限等待
- 添加条件请求支持 (If-Modified-Since/If-None-Match),处理 304 响应
- 添加 background_update_disable 配置,允许禁用后台更新
- 添加 cache_ignore_headers 配置,缓存时忽略指定响应头
- 添加 methods 配置,指定可缓存的 HTTP 方法
- 改进路径匹配逻辑,支持精确匹配和通配符匹配

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 18:23:20 +08:00
xfy
8baee13503 fix(proxy,config): 修复 HealthChecker 重启支持和补充 random 算法文档
Stop 后重建 stopCh 以支持再次 Start;config 注释补充 random 算法。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 11:41:16 +08:00
xfy
11f9cebcd5 fix(proxy): 修复 ProxyBind 拨号超时和 Cookie 属性匹配
ProxyBind 使用 MaxConnWaitTimeout 作为拨号超时不合理,改为默认 30s;
rewriteCookieAttr 属性匹配改为大小写不敏感;预分配 cookies 切片容量。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 11:41:03 +08:00
xfy
ce2d11197a test(loadbalance,proxy): 添加上游参数和 random 算法测试
新增 IsAvailable/RecordFailure/RecordSuccess/filterHealthy 备份优先级、
Random 负载均衡算法测试,适配 createHostClient 签名变更。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 11:28:59 +08:00
xfy
2b63666ea5 feat(proxy,server): 实现 ProxyBind/Buffering/ProxyURI 和响应头控制
ProxyBind 支持指定本地地址出站连接,Buffering 控制响应缓冲模式,
ProxyURI 实现 nginx proxy_pass URI 替换语义,
响应头新增 HideResponse/PassResponse/IgnoreHeaders/Cookie 域路径重写,
健康检查集成 RecordFailure/RecordSuccess 软失败状态。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 11:28:32 +08:00
xfy
ae0bec6c3b feat(internal): 实现 internal 指令
- 新增 IsInternalRedirect 检测内部重定向请求
- static handler 支持 internal 访问限制
- proxy handler 支持 internal 访问限制
- 支持 X-Accel-Redirect 内部重定向

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 18:09:06 +08:00
xfy
42a4c8d311 docs(proxy): 为反向代理模块添加标准化 godoc 注释
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 11:23:03 +08:00
xfy
0c71a80b5a docs(proxy): 为反向代理模块添加标准化 godoc 注释
为 proxy 包所有文件添加完整文档注释:
- proxy: 反向代理核心(负载均衡、缓存、WebSocket、SSL/TLS)
- headers: X-Forwarded 系列请求头设置
- health: 后端健康检查
- proxy_ssl: 上游 SSL/TLS 配置
- redirect_rewrite: 重定向响应改写
- tempfile_cleaner: 临时文件清理

包级注释详细说明支持的负载均衡算法、故障转移机制、
代理缓存策略、重定向改写模式等核心功能。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 10:59:35 +08:00
xfy
5f5717d6a4 test: 添加各模块覆盖率补充测试
- middleware/security: access 中间件覆盖率测试
- proxy: proxy 核心功能覆盖率测试
- server: server 扩展功能测试
- stream: stream 处理覆盖率测试

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 08:27:25 +08:00
xfy
4000d220f4 test(proxy): 添加 DNS 解析测试覆盖
- 测试 DNS 解析功能
- 测试解析超时处理
- 测试缓存和刷新机制

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 18:12:38 +08:00
xfy
bec8932561 feat(server): 添加缓存清理 API 支持
新增 PurgeHandler 处理器,支持:
- 按精确路径和通配符模式清理缓存
- HTTP 方法过滤(默认 GET)
- IP 白名单访问控制(CIDR/单 IP/localhost)
- Token 认证保护
- 三种启动模式路由注册

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 16:47:10 +08:00
xfy
326eedc729 perf(proxy,logging,compression): 使用零拷贝字节路径减少内存分配
- proxy: headersPool sync.Pool 复用 header map,容量 20
- proxy: buildCacheKeyHash 使用池化 map 替代 make(map[string]string)
- proxy: ServeHTTP 目标 URI 构造使用 []byte append + SetRequestURIBytes
- headers: X-Forwarded-For 构造使用 []byte append + SetBytesKV
- logging: Str() 改为 Bytes() 零拷贝日志字段
- compression: Process() 直接操作 []byte,使用 bytes.Contains/Equal/HasPrefix
- compression: isCompressible() 签名从 string 改为 []byte

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 13:50:15 +08:00
xfy
8a2e118ab8 test(proxy): 添加 WebSocket 代理性能基准测试
覆盖握手升级请求构建、不同帧大小转发吞吐量和心跳往返延迟。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 11:44:45 +08:00