Compare commits

..
10 Commits
Author SHA1 Message Date
meiseayoung 44ba82c194 chore: update v.mod version 2026-01-03 20:50:24 +08:00
meiseayoung 9eb360926b feat(usockets): optimize high concurrency support up to 10,000+ connections
- Increase uSockets listen() backlog from 512 to 16384 in bsd.c
- Add high concurrency test suite (5000-10000 concurrent connections)
- Add HIGH_CONCURRENCY.md documentation with optimization guide
- Add usockets/build.sh script for rebuilding uSockets library
- Update README with latest benchmark results

Performance (macOS M3 Max):
- 5,000 concurrent: 81,524 RPS, 100% success
- 10,000 concurrent: 24,198 RPS, 100% success

System requirements:
- kern.ipc.somaxconn >= 8192
- ulimit -n 65535
2026-01-03 20:45:30 +08:00
meiseayoung 3b8d21dd0d fix: update import path to VPM package name (meiseayoung.hono)
- Change all `import hono` to `import meiseayoung.hono` in code and docs
- Ensure compatibility with VPM installation via `v install meiseayoung.hono`
2026-01-02 22:05:12 +08:00
meiseayoung 43aae4f10d chore: update v.mod version 2026-01-02 21:51:01 +08:00
meiseayoung 05bb2d6c95 feat: cross-platform uSockets support and route cache optimization
1. Cross-platform uSockets configuration
   - Use @VMODROOT for portable library paths
   - Support macOS (arm64/x86_64), Windows, and Linux
   - Auto-detect Homebrew paths for libuv on macOS

2. Route cache optimization (3x performance boost)
   - Replace LRU cache with FastRouteCache for dynamic routes
   - Zero-overhead cache lookup (no TTL check, no LRU reordering)
   - Dynamic route performance: 30k -> 97k RPS

3. New test files
   - Go-based integration tests for picoev and uSockets
   - FastCache optimization validation tests
   - Benchmark comparison tools
2026-01-02 21:44:07 +08:00
meiseayoung 9aefe5714d chore: update v.mod version 2025-12-31 18:35:29 +08:00
meiseayoung 1fc22044c3 perf: optimize HTTP parsing with zero-allocation techniques
- Refactor parse_path_and_query() to use single-pass traversal instead of split()
- Add eq_ignore_case() and contains_ignore_case() to avoid to_lower() allocations
- Optimize HTTP method parsing with first-char branching (parse_http_method_fast)
- Optimize Keep-Alive header check to avoid string allocations
- Apply optimizations to all server backends: picoev, usockets, and app.v

Performance improvements:
- Query string parsing: 20-44% faster
- Keep-Alive check: 82-90% faster
- HTTP method parsing: eliminates string comparison overhead
- Response header processing: removes to_lower() allocations

All 20+ test suites pass with no regressions.
2025-12-31 18:34:46 +08:00
meiseayoung b478269d8e chore: update v.mod version 2025-12-31 17:38:29 +08:00
meiseayoung 69d1385ced perf: 0 middleware ignore copy 2025-12-31 17:37:51 +08:00
meiseayoung 1482b9c4d9 doc: add Framework Comparison 2025-12-31 16:04:44 +08:00
86 changed files with 4041 additions and 513 deletions
+34 -5
View File
@@ -91,7 +91,7 @@ The uSockets library and libuv are pre-compiled and included in the `usockets/li
### Using uSockets Backend
```v
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -110,11 +110,40 @@ fn main() {
See [benchmark/README.md](benchmark/README.md) for performance benchmarks and [usockets/README.md](usockets/README.md) for uSockets integration details.
## High Concurrency Support
v-hono with uSockets backend supports **10,000+ concurrent connections** out of the box.
### Performance Results
| Concurrent | RPS | Avg Latency | P99 Latency | Success Rate |
|------------|-----|-------------|-------------|--------------|
| 5,000 | 81,524 | 60.77ms | 295.17ms | 100% |
| 6,000 | 56,290 | 98.46ms | 557.47ms | 100% |
| 7,000 | 42,895 | 130.04ms | 824.80ms | 100% |
| 8,000 | 30,537 | 165.27ms | 1058.05ms | 100% |
| 9,000 | 28,693 | 215.86ms | 1422.67ms | 100% |
| 10,000 | 24,198 | 240.90ms | 1602.10ms | 100% |
### System Configuration (macOS)
For optimal high-concurrency performance:
```bash
# Increase socket backlog limit
sudo sysctl -w kern.ipc.somaxconn=8192
# Increase file descriptor limit
ulimit -n 65535
```
See [docs/HIGH_CONCURRENCY.md](docs/HIGH_CONCURRENCY.md) for detailed optimization guide.
## Quick Start
```v
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -146,7 +175,7 @@ fn main() {
```v
import net.http
import time
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -172,7 +201,7 @@ fn main() {
```v
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -200,7 +229,7 @@ fn main() {
```v
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
+95 -16
View File
@@ -40,6 +40,10 @@ pub mut:
use_fast_router bool = true // 新增:是否使用快速路由器
context_middlewares []ContextMiddleware
route_middlewares map[string][]ContextMiddleware // 路由前缀对应的中间件
// 优化:预排序的中间件前缀列表(启动时计算一次)
sorted_middleware_prefixes []string
// 优化:标记是否有中间件(用于零中间件快速路径)
has_middlewares bool
}
// Context 中间件类型
@@ -185,6 +189,14 @@ pub fn (mut app Hono) all(path string, handler fn (mut Context) http.Response) {
// Context 中间件
pub fn (mut app Hono) use(mw ContextMiddleware) {
app.context_middlewares << mw
app.has_middlewares = true
}
// 预计算中间件前缀排序(在服务器启动前调用)
pub fn (mut app Hono) precompute_middleware_prefixes() {
app.sorted_middleware_prefixes = app.route_middlewares.keys()
app.sorted_middleware_prefixes.sort(a.len < b.len)
app.has_middlewares = app.context_middlewares.len > 0 || app.route_middlewares.len > 0
}
// notFound() - 自定义 404 处理器
@@ -215,41 +227,53 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
}
}
// 解析 query
raw_query := url.query().to_map()
// 解析 query - 优化:直接使用 url.raw_query 避免额外解析
mut query_map := map[string]string{}
for key, values in raw_query {
if values.len > 0 {
query_map[key] = values[0]
}
if url.raw_query.len > 0 {
query_map = parse_query_string_app(url.raw_query)
}
// 缓存 method 字符串,避免多次调用 .str()
method_str := req.method.str()
// 尝试 Context 路由
// 优先使用快速路由器
if s.app.use_fast_router {
if route_match := s.app.fast_router.match_route(req.method.str(), url.path) {
if route_match := s.app.fast_router.match_route(method_str, url.path) {
// param 由路由匹配结果提供
param_map := route_match.params.clone()
// body
body := req.data
// 构造 Context
mut ctx := Context.new(req, param_map, query_map, body)
// 优化:零中间件快速路径
if !s.app.has_middlewares {
return route_match.handler.handle(mut ctx)
}
// 获取该路径对应的中间件
middlewares := s.get_middlewares_for_path(url.path)
// 洋葱模型递归执行中间件
return s.exec_context_middlewares_with_list(0, middlewares, mut ctx, fn [route_match] (mut c Context) http.Response {
return route_match.handler.handle(mut c)
})
})
}
// 如果快速路由器没有匹配,回退到混合路由器
if route_match := s.app.context_hybrid_router.match_route(req.method.str(), url.path) {
if route_match := s.app.context_hybrid_router.match_route(method_str, url.path) {
// param 由路由匹配结果提供
param_map := route_match.params.clone()
// body
body := req.data
// 构造 Context
mut ctx := Context.new(req, param_map, query_map, body)
// 优化:零中间件快速路径
if !s.app.has_middlewares {
return route_match.handler.handle(mut ctx)
}
// 获取该路径对应的中间件
middlewares := s.get_middlewares_for_path(url.path)
// 洋葱模型递归执行中间件
@@ -258,13 +282,19 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
})
}
} else {
if route_match := s.app.context_hybrid_router.match_route(req.method.str(), url.path) {
if route_match := s.app.context_hybrid_router.match_route(method_str, url.path) {
// param 由路由匹配结果提供
param_map := route_match.params.clone()
// body
body := req.data
// 构造 Context
mut ctx := Context.new(req, param_map, query_map, body)
// 优化:零中间件快速路径
if !s.app.has_middlewares {
return route_match.handler.handle(mut ctx)
}
// 获取该路径对应的中间件
middlewares := s.get_middlewares_for_path(url.path)
// 洋葱模型递归执行中间件
@@ -291,15 +321,17 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
})
}
// 获取路径对应的所有中间件(全局 + 路由前缀匹配的)
// 获取路径对应的所有中间件(全局 + 路由前缀匹配的)- 优化版
fn (s ServerHanler) get_middlewares_for_path(path string) []ContextMiddleware {
// 优化:只有全局中间件时,直接返回引用(避免克隆)
if s.app.route_middlewares.len == 0 {
return s.app.context_middlewares
}
mut middlewares := s.app.context_middlewares.clone()
// 按前缀长度排序,确保更具体的前缀后执行
mut prefixes := s.app.route_middlewares.keys()
prefixes.sort(a.len < b.len)
for prefix in prefixes {
// 优化:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
for prefix in s.app.sorted_middleware_prefixes {
if path.starts_with(prefix) || prefix == '/' {
if mws := s.app.route_middlewares[prefix] {
middlewares << mws
@@ -342,6 +374,9 @@ pub fn (mut app Hono) listen(port string) {
return
}
// 优化:预计算中间件前缀排序
app.precompute_middleware_prefixes()
// 使用优化配置的 picoev 高性能服务器(支持高并发)
app.listen_picoev_with_config(PicoevConfig{
port: port_num
@@ -372,6 +407,7 @@ pub fn (mut app Hono) route(prefix string, mut subapp Hono) {
} else {
app.route_middlewares[prefix] = subapp.context_middlewares.clone()
}
app.has_middlewares = true
}
// 继承子应用的 notFound 和 onError 处理器(如果主应用没有设置)
@@ -508,5 +544,48 @@ pub fn Hono.new() Hono {
fast_router: FastRouter.new()
use_fast_router: true
route_middlewares: map[string][]ContextMiddleware{}
sorted_middleware_prefixes: []string{}
has_middlewares: false
}
}
// 快速解析 query string(单次遍历,避免 split)- app.v 版本
@[inline]
fn parse_query_string_app(query_str string) map[string]string {
mut query_map := map[string]string{}
len := query_str.len
if len == 0 {
return query_map
}
mut key_start := 0
mut key_end := -1
mut value_start := -1
for i := 0; i <= len; i++ {
ch := if i < len { query_str[i] } else { `&` } // 末尾视为分隔符
if ch == `=` && key_end == -1 {
key_end = i
value_start = i + 1
} else if ch == `&` {
// 完成一个键值对
if key_end > key_start && value_start > 0 {
key := query_str[key_start..key_end]
value := if value_start < i { query_str[value_start..i] } else { '' }
query_map[key] = value
} else if key_end == -1 && i > key_start {
// 只有 key 没有 value
key := query_str[key_start..i]
query_map[key] = ''
}
// 重置状态
key_start = i + 1
key_end = -1
value_start = -1
}
}
return query_map
}
+10 -18
View File
@@ -2,27 +2,19 @@
Performance benchmarks for V-Hono web framework.
## Backend Comparison
## Framework Comparison (500 connections, 100K requests)
### uSockets vs Picoev (200 connections, 100K requests)
| Framework | RPS | Errors | Avg Latency | P50 | P95 | P99 |
|-----------|-----|--------|-------------|-----|-----|-----|
| **v-hono (uSockets)** | **20,231** | **0** | **24.62ms** | **23.65ms** | **33.82ms** | **57.29ms** |
| v-hono (picoev) | 16,177 | 0 | 30.75ms | 26.25ms | 35.37ms | 111.38ms |
| veb (V官方) | 7,278 | 772 | 68.06ms | 55.79ms | 71.62ms | 98.90ms |
| Backend | RPS | Avg Latency | P95 | P99 |
|---------|-----|-------------|-----|-----|
| uSockets | ~22,000 | 8.75ms | 16.66ms | 25.73ms |
| picoev | ~15,000 | 13.36ms | 18.89ms | 31.66ms |
### Performance Summary
**uSockets provides ~50% higher throughput under high concurrency.**
### High Concurrency Test (500 connections, 100K requests)
| Metric | uSockets |
|--------|----------|
| RPS | ~20,000 |
| Errors | 0 |
| Avg Latency | 25.04ms |
| P50 | 24.32ms |
| P95 | 32.97ms |
| P99 | 64.59ms |
- **v-hono (uSockets) vs veb**: **2.78x faster**, zero errors
- **v-hono (uSockets) vs picoev**: **25% faster**, better P99 latency
- **v-hono (picoev) vs veb**: **2.22x faster**, zero errors
## Running Benchmarks
+1 -1
View File
@@ -7,7 +7,7 @@
module main
import hono
import meiseayoung.hono
import net.http
fn main() {
+68
View File
@@ -336,3 +336,71 @@ pub fn (mut cache ContextLRUCache) clear() {
cache.size = 0
cache.last_cleanup = time.now().unix()
}
// ============================================================================
// 高性能路由缓存 - 专为路由匹配优化
// ============================================================================
// 特点:
// 1. 无 TTL 检查(路由不会过期)
// 2. 无 LRU 移动(简单 map 查找)
// 3. 固定大小,满了就清空重建
// 4. 零开销的 get 操作
pub struct FastRouteCache {
mut:
cache map[string]ContextRouteMatch
capacity int
enabled bool = true
}
pub fn FastRouteCache.new(capacity int) FastRouteCache {
return FastRouteCache{
cache: map[string]ContextRouteMatch{}
capacity: capacity
enabled: true
}
}
// 快速获取 - 零开销
@[inline]
pub fn (cache &FastRouteCache) get(key string) ?ContextRouteMatch {
if !cache.enabled {
return none
}
if result := cache.cache[key] {
return result
}
return none
}
// 快速设置
@[inline]
pub fn (mut cache FastRouteCache) put(key string, value ContextRouteMatch) {
if !cache.enabled {
return
}
// 如果满了,清空重建(比 LRU 淘汰更快)
if cache.cache.len >= cache.capacity {
cache.cache.clear()
}
cache.cache[key] = value
}
// 获取统计
pub fn (cache &FastRouteCache) get_stats() (int, int) {
return cache.cache.len, cache.capacity
}
// 清空缓存
pub fn (mut cache FastRouteCache) clear() {
cache.cache.clear()
}
// 启用/禁用
pub fn (mut cache FastRouteCache) set_enabled(enabled bool) {
cache.enabled = enabled
if !enabled {
cache.clear()
}
}
+115
View File
@@ -0,0 +1,115 @@
# v-hono 高并发优化指南
## 概述
v-hono 使用 uSockets 作为高性能网络后端,经过优化后可以稳定支持 **10,000+ 并发连接**。
## 性能测试结果
| 并发数 | RPS | 平均延迟 | P99延迟 | 成功率 |
|--------|-----|----------|---------|--------|
| 5,000 | 81,524 | 60.77ms | 295.17ms | 100% |
| 6,000 | 56,290 | 98.46ms | 557.47ms | 100% |
| 7,000 | 42,895 | 130.04ms | 824.80ms | 100% |
| 8,000 | 30,537 | 165.27ms | 1058.05ms | 100% |
| 9,000 | 28,693 | 215.86ms | 1422.67ms | 100% |
| 10,000 | 24,198 | 240.90ms | 1602.10ms | 100% |
测试环境:macOS (Apple Silicon M3 Max)
**重要提示**:每次测试后需等待 60 秒让 TIME_WAIT 连接释放,否则会影响下一次测试结果。
## 关键优化
### 1. uSockets backlog 参数
原始 uSockets 库的 `listen()` backlog 参数硬编码为 512,限制了高并发能力。
**修复位置**:`v-hono/usockets/src/bsd.c` (第 532 行和第 578 行)
```c
// 修改前
listen(listenFd, 512)
// 修改后
listen(listenFd, 16384)
```
修改后的源码保存在 `v-hono/usockets/src/bsd.c`,编译后的库文件在 `v-hono/lib/libusockets_full.a`。
**重新编译**:运行 `v-hono/usockets/build.sh` 脚本。
### 2. 系统参数配置
macOS 需要调整以下系统参数:
```bash
# 查看当前值
sysctl kern.ipc.somaxconn
# 临时修改(重启后失效)
sudo sysctl -w kern.ipc.somaxconn=8192
# 永久修改(添加到 /etc/sysctl.conf)
kern.ipc.somaxconn=8192
```
**注意**:实际 backlog 值会被 `kern.ipc.somaxconn` 截断,所以系统参数也需要相应调整。
## 重新编译 uSockets(可选)
如果需要自定义 backlog 值,可以重新编译 uSockets:
```bash
# 1. 克隆 uSockets
git clone https://github.com/uNetworking/uSockets.git
# 2. 修改 src/bsd.c 中的 listen 调用
# 将 listen(listenFd, 512) 改为 listen(listenFd, 16384)
# 3. 编译(macOS with libuv)
WITH_LIBUV=1 CFLAGS="-I/opt/homebrew/include" make
# 4. 复制到 v-hono
cp uSockets.a /path/to/v-hono/lib/libusockets_full.a
# 5. 重新编译 v-hono 应用
v -enable-globals -prod -o your_app your_app.v
```
## 使用建议
1. **生产环境**:建议使用 uSockets 后端(`app.listen_usockets(port)`)
2. **系统调优**:确保 `kern.ipc.somaxconn` >= 8192
3. **文件描述符**:服务器和客户端都需要设置 `ulimit -n 65535`
4. **启动命令**:`ulimit -n 65535 && ./your_server`
## 高并发测试
运行高并发测试:
```bash
# 启动服务器
ulimit -n 65535 && ./bench_server_usockets
# 运行测试 (5000-10000 并发)
ulimit -n 65535 && go run v-hono/tests/test_high_concurrency.go
# 单独测试某个级别
ulimit -n 65535 && go run v-hono/tests/test_high_concurrency.go 8000
```
## 问题排查
如果高并发测试失败,检查:
1. 服务器是否正常响应:`curl http://localhost:8080/health`
2. 系统参数:`sysctl kern.ipc.somaxconn`
3. 文件描述符限制:`ulimit -n`
4. 测试客户端是否有端口耗尽问题
## 版本信息
- uSockets backlog: 16384
- 测试日期: 2026-01-03
- 测试通过最大并发: 10,000(不使用渐进式启动)
+1 -1
View File
@@ -11,7 +11,7 @@
#### 使用方式
```v
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
+1 -1
View File
@@ -1,6 +1,6 @@
module main
import hono
import meiseayoung.hono
import net.http
import x.json2
+1 -1
View File
@@ -4,7 +4,7 @@
module main
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
+1 -1
View File
@@ -9,7 +9,7 @@
module main
import time
import hono
import meiseayoung.hono
import net.http
// ============================================
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
fn main() {
+1 -1
View File
@@ -3,7 +3,7 @@ module main
import net.http
import time
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
+1 -1
View File
@@ -1,7 +1,7 @@
module main
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
+1 -1
View File
@@ -1,6 +1,6 @@
module main
import hono
import meiseayoung.hono
import net.http
fn main() {
+1 -1
View File
@@ -2,7 +2,7 @@
module main
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -12,7 +12,7 @@
// ```
import net.http
import hono
import meiseayoung.hono
fn main() {
println('🚀 V-Hono 路由分组示例启动中...')
@@ -2,7 +2,7 @@
// 演示新功能:子应用中间件继承、all() 方法、notFound/onError 处理器
import net.http
import hono
import meiseayoung.hono
fn main() {
println('🚀 V-Hono 路由分组增强示例启动中...')
+1 -1
View File
@@ -4,7 +4,7 @@
module main
import hono
import meiseayoung.hono
import net.http
fn main() {
+1 -1
View File
@@ -4,7 +4,7 @@
module main
import hono
import meiseayoung.hono
import net.http
fn main() {
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import os
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import os
import time
+1 -1
View File
@@ -1,7 +1,7 @@
// 测试服务器 - 用于高并发测试
module main
import hono
import meiseayoung.hono
import net.http
fn main() {
+1 -1
View File
@@ -1,7 +1,7 @@
module main
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
+26 -11
View File
@@ -27,10 +27,12 @@ pub mut:
static_routes map[string]IHandler
static_route_results map[string]ContextRouteMatch // 预分配的静态路由结果
precompiled_routes []PrecompiledRoute
lru_cache ContextLRUCache // 使用 LRU 缓存替代简单 map
fast_cache FastRouteCache // 使用高性能缓存替代 LRU
lru_cache ContextLRUCache // 保留 LRU 缓存用于兼容
regex_cache map[string]FastCompiledRegex // 正则表达式缓存
cache_enabled bool = true
sort_enabled bool = true // 是否启用路由排序
use_fast_cache bool = true // 是否使用高性能缓存
}
// 创建快速路由器
@@ -39,8 +41,10 @@ pub fn FastRouter.new() FastRouter {
static_routes: map[string]IHandler{}
static_route_results: map[string]ContextRouteMatch{}
precompiled_routes: []PrecompiledRoute{}
lru_cache: ContextLRUCache.new(1000) // 默认1000条缓存
fast_cache: FastRouteCache.new(10000) // 高性能缓存,10000条
lru_cache: ContextLRUCache.new(1000) // LRU 缓存保留兼容
regex_cache: map[string]FastCompiledRegex{}
use_fast_cache: true
}
}
@@ -50,8 +54,10 @@ pub fn FastRouter.new_with_cache_size(cache_size int) FastRouter {
static_routes: map[string]IHandler{}
static_route_results: map[string]ContextRouteMatch{}
precompiled_routes: []PrecompiledRoute{}
fast_cache: FastRouteCache.new(cache_size * 10) // 高性能缓存
lru_cache: ContextLRUCache.new(cache_size)
regex_cache: map[string]FastCompiledRegex{}
use_fast_cache: true
}
}
@@ -171,17 +177,23 @@ fn (router FastRouter) precompile_route(method string, handler IHandler) !Precom
}
}
// 快速路由匹配(优化版:静态路由跳过缓存 + 预分配结果)
// 快速路由匹配(优化版:静态路由跳过缓存 + 预分配结果 + 高性能缓存)
pub fn (mut router FastRouter) match_route(method string, path string) ?ContextRouteMatch {
// 优化:只拼接一次 cache key,复用于静态路由和缓存查找
cache_key := '${method}:${path}'
// 1. 静态路由直接返回预分配的结果(零分配)
static_key := '${method}:${path}'
if result := router.static_route_results[static_key] {
if result := router.static_route_results[cache_key] {
return result
}
// 2. 动态路由先检查 LRU 缓存(避免重复正则匹配)
if router.cache_enabled {
cache_key := '${method}:${path}'
// 2. 动态路由先检查高性能缓存(零开销查找)
if router.cache_enabled && router.use_fast_cache {
if cached := router.fast_cache.get(cache_key) {
return cached
}
} else if router.cache_enabled {
// 回退到 LRU 缓存
if cached := router.lru_cache.get(cache_key) {
return cached
}
@@ -208,10 +220,13 @@ pub fn (mut router FastRouter) match_route(method string, path string) ?ContextR
base_path: ''
}
// 只缓存动态路由结果
// 缓存动态路由结果
if router.cache_enabled {
cache_key := '${method}:${path}'
router.lru_cache.put(cache_key, result)
if router.use_fast_cache {
router.fast_cache.put(cache_key, result)
} else {
router.lru_cache.put(cache_key, result)
}
}
return result
+199 -45
View File
@@ -79,7 +79,15 @@ fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picoht
if ctx.app.use_fast_router {
if route_match := ctx.app.fast_router.match_route(method_str, path) {
mut hono_ctx := create_picoev_context(req, route_match.params, query_map)
middlewares := get_middlewares_for_path_picoev(ctx.app, path)
// 优化:零中间件快速路径
if !ctx.app.has_middlewares {
response := route_match.handler.handle(mut hono_ctx)
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
return
}
middlewares := get_middlewares_for_path_picoev_optimized(ctx.app, path)
response := exec_middlewares_picoev(0, middlewares, mut hono_ctx, route_match.handler)
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
return
@@ -89,7 +97,15 @@ fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picoht
// 回退到混合路由器
if route_match := ctx.app.context_hybrid_router.match_route(method_str, path) {
mut hono_ctx := create_picoev_context(req, route_match.params, query_map)
middlewares := get_middlewares_for_path_picoev(ctx.app, path)
// 优化:零中间件快速路径
if !ctx.app.has_middlewares {
response := route_match.handler.handle(mut hono_ctx)
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
return
}
middlewares := get_middlewares_for_path_picoev_optimized(ctx.app, path)
response := exec_middlewares_picoev(0, middlewares, mut hono_ctx, route_match.handler)
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
return
@@ -118,25 +134,76 @@ fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picoht
res.end()
}
// 检查客户端是否请求 Keep-Alive
// 检查客户端是否请求 Keep-Alive - 优化版
// 避免 to_lower() 创建新字符串,使用大小写不敏感比较
fn check_keepalive_request(req picohttpparser.Request) bool {
for i in 0 .. req.num_headers {
h := req.headers[i]
if h.name.to_lower() == 'connection' {
return h.value.to_lower().contains('keep-alive')
// 大小写不敏感比较 "connection"
if h.name.len == 10 && eq_ignore_case(h.name, 'connection') {
// 检查是否包含 "keep-alive"(大小写不敏感)
return contains_ignore_case(h.value, 'keep-alive')
}
}
return true // HTTP/1.1 默认 Keep-Alive
}
// 获取路径对应的所有中间件
fn get_middlewares_for_path_picoev(app &Hono, path string) []ContextMiddleware {
// 大小写不敏感字符串比较(避免分配)
@[inline]
fn eq_ignore_case(a string, b string) bool {
if a.len != b.len {
return false
}
for i in 0 .. a.len {
ca := a[i]
cb := b[i]
// 转换为小写比较
la := if ca >= `A` && ca <= `Z` { ca + 32 } else { ca }
lb := if cb >= `A` && cb <= `Z` { cb + 32 } else { cb }
if la != lb {
return false
}
}
return true
}
// 大小写不敏感的 contains 检查(避免分配)
@[inline]
fn contains_ignore_case(haystack string, needle string) bool {
if needle.len > haystack.len {
return false
}
max_start := haystack.len - needle.len
for i := 0; i <= max_start; i++ {
mut found := true
for j in 0 .. needle.len {
ch := haystack[i + j]
cn := needle[j]
lh := if ch >= `A` && ch <= `Z` { ch + 32 } else { ch }
ln := if cn >= `A` && cn <= `Z` { cn + 32 } else { cn }
if lh != ln {
found = false
break
}
}
if found {
return true
}
}
return false
}
// 获取路径对应的所有中间件(优化版:使用预排序的前缀列表)
fn get_middlewares_for_path_picoev_optimized(app &Hono, path string) []ContextMiddleware {
// 优化:只有全局中间件时,直接返回引用(避免克隆)
if app.route_middlewares.len == 0 {
return app.context_middlewares
}
mut middlewares := app.context_middlewares.clone()
mut prefixes := app.route_middlewares.keys()
prefixes.sort(a.len < b.len)
for prefix in prefixes {
// 优化:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
for prefix in app.sorted_middleware_prefixes {
if path.starts_with(prefix) || prefix == '/' {
if mws := app.route_middlewares[prefix] {
middlewares << mws
@@ -147,6 +214,11 @@ fn get_middlewares_for_path_picoev(app &Hono, path string) []ContextMiddleware {
return middlewares
}
// 获取路径对应的所有中间件(保留旧版本兼容)
fn get_middlewares_for_path_picoev(app &Hono, path string) []ContextMiddleware {
return get_middlewares_for_path_picoev_optimized(app, path)
}
// 执行中间件链
fn exec_middlewares_picoev(idx int, middlewares []ContextMiddleware, mut ctx Context, handler IHandler) http.Response {
if idx < middlewares.len {
@@ -158,40 +230,96 @@ fn exec_middlewares_picoev(idx int, middlewares []ContextMiddleware, mut ctx Con
return handler.handle(mut ctx)
}
// 解析路径和查询参数
// 解析路径和查询参数 - 零分配优化版
// 使用指针遍历避免创建临时数组
fn parse_path_and_query(full_path string) (string, map[string]string) {
mut query_map := map[string]string{}
len := full_path.len
if idx := full_path.index('?') {
path := full_path[..idx]
query_str := full_path[idx + 1..]
for part in query_str.split('&') {
if eq_idx := part.index('=') {
query_map[part[..eq_idx]] = part[eq_idx + 1..]
}
}
return path, query_map
if len == 0 {
return full_path, query_map
}
return full_path, query_map
// 快速路径:大多数请求没有查询参数
// 从后向前搜索 '?' 通常更快(查询参数在末尾)
mut query_start := -1
for i := len - 1; i >= 0; i-- {
if full_path[i] == `?` {
query_start = i
break
}
}
// 没有查询参数,直接返回(最常见情况)
if query_start == -1 {
return full_path, query_map
}
path := full_path[..query_start]
// 解析查询参数(单次遍历,避免 split)
mut key_start := query_start + 1
mut key_end := -1
mut value_start := -1
for i := query_start + 1; i <= len; i++ {
ch := if i < len { full_path[i] } else { `&` } // 末尾视为分隔符
if ch == `=` && key_end == -1 {
key_end = i
value_start = i + 1
} else if ch == `&` {
// 完成一个键值对
if key_end > key_start && value_start > 0 {
key := full_path[key_start..key_end]
value := if value_start < i { full_path[value_start..i] } else { '' }
query_map[key] = value
} else if key_end == -1 && i > key_start {
// 只有 key 没有 value(如 ?foo&bar=1)
key := full_path[key_start..i]
query_map[key] = ''
}
// 重置状态
key_start = i + 1
key_end = -1
value_start = -1
}
}
return path, query_map
}
// 创建 picoev 上下文
// 创建 picoev 上下文 - 优化版
// 延迟转换 http.Request,只在真正需要时才转换
fn create_picoev_context(req picohttpparser.Request, params map[string]string, query map[string]string) Context {
// 提取纯路径(不含查询参数)
path := extract_path_only(req.path)
return Context{
req: convert_picoev_request(req)
params: params
query: query
body: req.body
url: req.path
path: req.path
path: path
status_code: 200
headers: map[string]string{}
}
}
// 转换 picoev 请求
// 快速提取路径(不含查询参数)
@[inline]
fn extract_path_only(full_path string) string {
for i in 0 .. full_path.len {
if full_path[i] == `?` {
return full_path[..i]
}
}
return full_path
}
// 转换 picoev 请求 - 优化版
// 使用预计算的方法映射避免字符串比较
fn convert_picoev_request(req picohttpparser.Request) http.Request {
mut headers := http.new_header()
@@ -201,23 +329,46 @@ fn convert_picoev_request(req picohttpparser.Request) http.Request {
}
return http.Request{
method: match req.method {
'GET' { http.Method.get }
'POST' { http.Method.post }
'PUT' { http.Method.put }
'DELETE' { http.Method.delete }
'PATCH' { http.Method.patch }
'HEAD' { http.Method.head }
'OPTIONS' { http.Method.options }
else { http.Method.get }
}
method: parse_http_method_fast(req.method)
url: req.path
data: req.body
header: headers
}
}
// 发送 picoev 响应
// 快速 HTTP 方法解析(基于首字符和长度)
@[inline]
fn parse_http_method_fast(method string) http.Method {
len := method.len
if len == 0 {
return http.Method.get
}
// 基于首字符快速分支
match method[0] {
`G` {
if len == 3 { return http.Method.get }
}
`P` {
if len == 4 && method[1] == `O` { return http.Method.post }
if len == 3 && method[1] == `U` { return http.Method.put }
if len == 5 { return http.Method.patch }
}
`D` {
if len == 6 { return http.Method.delete }
}
`H` {
if len == 4 { return http.Method.head }
}
`O` {
if len == 7 { return http.Method.options }
}
else {}
}
return http.Method.get
}
// 发送 picoev 响应 - 优化版
fn send_picoev_response(mut res picohttpparser.Response, ctx Context, response http.Response, keepalive bool, config PicoevConfig) {
status_code := if ctx.status_code != 0 { ctx.status_code } else { response.status_code }
@@ -231,18 +382,21 @@ fn send_picoev_response(mut res picohttpparser.Response, ctx Context, response h
mut has_connection := false
for key, value in ctx.headers {
// 跳过 Content-Length,picohttpparser 会在 body() 时自动添加
if key.to_lower() == 'content-length' {
continue
// 使用快速大小写不敏感比较
key_len := key.len
if key_len == 14 && eq_ignore_case(key, 'content-length') {
continue // 跳过 Content-Length
}
res.header(key, value)
key_lower := key.to_lower()
if key_lower == 'content-type' { has_content_type = true }
if key_lower == 'connection' { has_connection = true }
if key_len == 12 && eq_ignore_case(key, 'content-type') {
has_content_type = true
} else if key_len == 10 && eq_ignore_case(key, 'connection') {
has_connection = true
}
}
if content_type := response.header.get(.content_type) {
if !has_content_type {
if !has_content_type {
if content_type := response.header.get(.content_type) {
res.header('Content-Type', content_type)
has_content_type = true
}
+26 -18
View File
@@ -208,10 +208,34 @@ pub fn (router ContextHybridRouter) match_static_route(method string, path strin
return none
}
// Context 版本的动态路径匹配
// Context 版本的动态路径匹配(保留旧版本兼容)
fn (mut router ContextHybridRouter) match_dynamic_route(method string, path string) ?ContextRouteMatch {
// 先检查缓存
cache_key := '${method}:${path}'
return router.match_dynamic_route_with_key(cache_key, method, path)
}
// Context 版本的主匹配函数(优化版:复用 cache key)
pub fn (mut router ContextHybridRouter) match_route(method string, path string) ?ContextRouteMatch {
// 优化:只拼接一次 cache key
cache_key := '${method}:${path}'
// 1. 先尝试静态路径匹配(最快)
if cache_key in router.static_routes {
return ContextRouteMatch{
handler: router.static_routes[cache_key]
params: map[string]string{}
path: path
base_path: ''
}
}
// 2. 再尝试动态路径匹配(复用 cache_key)
return router.match_dynamic_route_with_key(cache_key, method, path)
}
// Context 版本的动态路径匹配(优化版:接收预计算的 cache_key)
fn (mut router ContextHybridRouter) match_dynamic_route_with_key(cache_key string, method string, path string) ?ContextRouteMatch {
// 先检查缓存
if cached := router.cache.get(cache_key) {
return cached
}
@@ -240,22 +264,6 @@ fn (mut router ContextHybridRouter) match_dynamic_route(method string, path stri
return none
}
// Context 版本的主匹配函数
pub fn (mut router ContextHybridRouter) match_route(method string, path string) ?ContextRouteMatch {
// 1. 先尝试静态路径匹配(最快)
if static_handler := router.match_static_route(method, path) {
return ContextRouteMatch{
handler: static_handler
params: map[string]string{}
path: path
base_path: ''
}
}
// 2. 再尝试动态路径匹配
return router.match_dynamic_route(method, path)
}
// Context 版本的获取所有路由
pub fn (router ContextHybridRouter) get_all_routes() ([]string, []string) {
mut static_paths := []string{}
+251
View File
@@ -0,0 +1,251 @@
// 高并发基准测试 - 用于对比 v-hono 内外性能
// 参数与外层 benchmark.go 保持一致: 500 并发, 100万请求
//
// 使用方法:
// 1. 启动服务器: v -enable-globals run v-hono/tests/test_picoev_server.v
// 2. 运行测试: go run v-hono/tests/benchmark_compare.go
package main
import (
"fmt"
"io"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
baseURL = "http://127.0.0.1:9999"
connections = 500
requests = 1000000
timeout = 10 * time.Second
)
type Metrics struct {
TotalRequests int64
SuccessRequests int64
FailedRequests int64
TotalBytes int64
MinLatency time.Duration
MaxLatency time.Duration
TotalLatencyNs int64
StartTime time.Time
EndTime time.Time
}
func main() {
fmt.Println("🔥 V-Hono 高并发基准测试")
fmt.Println(strings.Repeat("=", 50))
fmt.Printf("服务器: %s\n", baseURL)
fmt.Printf("并发数: %d\n", connections)
fmt.Printf("请求数: %d\n", requests)
fmt.Printf("超时: %v\n", timeout)
fmt.Println()
// 检查服务器
if !checkServer() {
fmt.Println("❌ 服务器未运行")
fmt.Println(" 请先启动: v -enable-globals run v-hono/tests/test_picoev_server.v")
return
}
fmt.Println("✅ 服务器已就绪")
// 预热
fmt.Println("\n🔥 预热服务器...")
warmup()
fmt.Println("✅ 预热完成")
// 运行测试
testCases := []struct {
name string
path string
}{
{"健康检查", "/health"},
{"根路径", "/"},
{"JSON接口", "/json"},
{"动态路由", "/users/123"},
}
allResults := make(map[string]*Metrics)
for _, tc := range testCases {
fmt.Printf("\n🚀 测试: %s (%s)\n", tc.name, tc.path)
fmt.Println(strings.Repeat("-", 50))
metrics := runBenchmark(tc.path)
allResults[tc.name] = metrics
printMetrics(tc.name, metrics)
time.Sleep(2 * time.Second)
}
// 汇总
printSummary(allResults)
}
func checkServer() bool {
client := &http.Client{Timeout: 2 * time.Second}
for i := 0; i < 3; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil && resp.StatusCode == 200 {
resp.Body.Close()
return true
}
time.Sleep(500 * time.Millisecond)
}
return false
}
func warmup() {
client := &http.Client{Timeout: 5 * time.Second}
for i := 0; i < 100; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}
}
func runBenchmark(endpoint string) *Metrics {
url := baseURL + endpoint
metrics := &Metrics{
StartTime: time.Now(),
MinLatency: time.Hour,
}
client := &http.Client{
Timeout: timeout,
Transport: &http.Transport{
MaxIdleConns: connections,
MaxIdleConnsPerHost: connections,
IdleConnTimeout: 30 * time.Second,
},
}
requestsPerWorker := requests / connections
var wg sync.WaitGroup
var latencyMutex sync.Mutex
// 进度显示
done := make(chan bool)
go showProgress(metrics, done)
// 启动工作协程
for i := 0; i < connections; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < requestsPerWorker; j++ {
start := time.Now()
resp, err := client.Get(url)
latency := time.Since(start)
atomic.AddInt64(&metrics.TotalRequests, 1)
atomic.AddInt64(&metrics.TotalLatencyNs, int64(latency))
latencyMutex.Lock()
if latency < metrics.MinLatency {
metrics.MinLatency = latency
}
if latency > metrics.MaxLatency {
metrics.MaxLatency = latency
}
latencyMutex.Unlock()
if err != nil {
atomic.AddInt64(&metrics.FailedRequests, 1)
continue
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil || resp.StatusCode >= 400 {
atomic.AddInt64(&metrics.FailedRequests, 1)
} else {
atomic.AddInt64(&metrics.SuccessRequests, 1)
atomic.AddInt64(&metrics.TotalBytes, int64(len(body)))
}
}
}()
}
wg.Wait()
metrics.EndTime = time.Now()
done <- true
return metrics
}
func showProgress(metrics *Metrics, done chan bool) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-done:
fmt.Println()
return
case <-ticker.C:
current := atomic.LoadInt64(&metrics.TotalRequests)
elapsed := time.Since(metrics.StartTime).Seconds()
rps := float64(current) / elapsed
progress := float64(current) / float64(requests) * 100
fmt.Printf("\r进度: %.1f%% | 完成: %d | RPS: %.0f | 耗时: %.1fs",
progress, current, rps, elapsed)
}
}
}
func printMetrics(name string, m *Metrics) {
duration := m.EndTime.Sub(m.StartTime)
avgLatency := time.Duration(m.TotalLatencyNs / m.TotalRequests)
fmt.Printf("\n📊 %s - 测试结果\n", name)
fmt.Println(strings.Repeat("=", 40))
fmt.Printf("总请求数: %d\n", m.TotalRequests)
fmt.Printf("成功请求: %d\n", m.SuccessRequests)
fmt.Printf("失败请求: %d\n", m.FailedRequests)
fmt.Printf("成功率: %.2f%%\n", float64(m.SuccessRequests)/float64(m.TotalRequests)*100)
fmt.Printf("总耗时: %.2f 秒\n", duration.Seconds())
fmt.Printf("RPS: %.0f 请求/秒\n", float64(m.TotalRequests)/duration.Seconds())
fmt.Printf("最小延迟: %v\n", m.MinLatency)
fmt.Printf("最大延迟: %v\n", m.MaxLatency)
fmt.Printf("平均延迟: %v\n", avgLatency)
if m.TotalBytes > 0 {
throughputMB := float64(m.TotalBytes) / 1024 / 1024 / duration.Seconds()
fmt.Printf("数据传输: %.2f MB\n", float64(m.TotalBytes)/1024/1024)
fmt.Printf("吞吐量: %.2f MB/s\n", throughputMB)
}
}
func printSummary(results map[string]*Metrics) {
fmt.Printf("\n🏆 性能汇总报告\n")
fmt.Println(strings.Repeat("=", 60))
fmt.Printf("%-15s %-12s %-10s %-12s %-10s\n", "接口", "RPS", "成功率", "平均延迟", "吞吐量")
fmt.Println(strings.Repeat("-", 60))
for name, metrics := range results {
duration := metrics.EndTime.Sub(metrics.StartTime)
rps := float64(metrics.TotalRequests) / duration.Seconds()
successRate := float64(metrics.SuccessRequests) / float64(metrics.TotalRequests) * 100
avgLatency := time.Duration(metrics.TotalLatencyNs / metrics.TotalRequests)
throughput := float64(metrics.TotalBytes) / 1024 / 1024 / duration.Seconds()
fmt.Printf("%-15s %-12.0f %-9.1f%% %-12v %-8.1fMB/s\n",
name, rps, successRate, avgLatency, throughput)
}
fmt.Println("\n✅ 测试完成!")
}
+1 -1
View File
@@ -3,7 +3,7 @@
module main
import time
import hono
import meiseayoung.hono
import net.http
const iterations = 100_000
+1 -1
View File
@@ -4,7 +4,7 @@
module main
import time
import hono
import meiseayoung.hono
import net.http
// ============================================
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import time
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import os
import time
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
fn main() {
println('=== 测试缓存内存泄漏修复 ===')
+81
View File
@@ -0,0 +1,81 @@
// 测试缓存命中率
module main
import meiseayoung.hono
import net.http
import time
fn main() {
println('=== 缓存命中率测试 ===')
mut app := hono.Hono.new()
app.get('/users/:id', fn (mut c hono.Context) http.Response {
user_id := c.params['id'] or { 'unknown' }
return c.json('{"user_id": "${user_id}"}')
})
// 获取 FastRouter 引用
mut router := app.fast_router
// 预热:先匹配一次让缓存生效
println('\n1. 预热阶段')
_ := router.match_route('GET', '/users/123')
// 获取初始统计
cache_size, cache_capacity := router.get_cache_stats()
println(' 缓存大小: ${cache_size}/${cache_capacity}')
// 测试相同路径的匹配
println('\n2. 测试相同路径 /users/123 匹配 1000 次')
sw := time.new_stopwatch()
for _ in 0 .. 1000 {
_ := router.match_route('GET', '/users/123')
}
elapsed := sw.elapsed()
println(' 耗时: ${elapsed.microseconds()}μs')
println(' 平均: ${elapsed.microseconds() / 1000}μs/次')
// 获取缓存统计
cache_size2, _ := router.get_cache_stats()
println(' 缓存大小: ${cache_size2}')
// 测试不同路径
println('\n3. 测试不同路径 /users/1 到 /users/1000')
sw2 := time.new_stopwatch()
for i in 1 .. 1001 {
_ := router.match_route('GET', '/users/${i}')
}
elapsed2 := sw2.elapsed()
println(' 耗时: ${elapsed2.microseconds()}μs')
println(' 平均: ${elapsed2.microseconds() / 1000}μs/次')
// 获取最终缓存统计
cache_size3, _ := router.get_cache_stats()
println(' 缓存大小: ${cache_size3}')
// 再次测试相同路径(应该命中缓存)
println('\n4. 再次测试 /users/500(应该命中缓存)')
sw3 := time.new_stopwatch()
for _ in 0 .. 1000 {
_ := router.match_route('GET', '/users/500')
}
elapsed3 := sw3.elapsed()
println(' 耗时: ${elapsed3.microseconds()}μs')
println(' 平均: ${elapsed3.microseconds() / 1000}μs/次')
// 详细统计
println('\n5. 详细统计')
stats := router.get_detailed_stats()
for key, value in stats {
println(' ${key}: ${value}')
}
println('\n=== 测试完成 ===')
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import strings
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
fn test_default_config() {
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
fn main() {
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import time
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
fn main() {
+381
View File
@@ -0,0 +1,381 @@
// FastCache 优化测试
// 验证高性能缓存的正确性和性能
module main
import meiseayoung.hono
import net.http
import time
struct TestResult {
mut:
name string
passed bool
detail string
}
fn main() {
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ FastCache 优化测试 ║')
println('╚═══════════════════════════════════════════════════════════════╝')
println('')
mut results := []TestResult{}
// 1. 基本功能测试
results << test_basic_cache_operations()
// 2. 路由匹配正确性测试
results << test_route_matching_correctness()
// 3. 参数提取正确性测试
results << test_param_extraction()
// 4. 缓存命中测试
results << test_cache_hit()
// 5. 缓存容量测试
results << test_cache_capacity()
// 6. 多路由并发测试
results << test_multiple_routes()
// 7. 性能基准测试
results << test_performance_benchmark()
// 8. 缓存一致性测试
results << test_cache_consistency()
// 打印结果
println('')
println('═══════════════════════════════════════════════════════════════')
println('📊 测试结果汇总')
println('═══════════════════════════════════════════════════════════════')
mut passed := 0
mut failed := 0
for result in results {
status := if result.passed { '✅' } else { '❌' }
println('${status} ${result.name}')
if result.detail.len > 0 {
println(' ${result.detail}')
}
if result.passed {
passed++
} else {
failed++
}
}
println('')
println('总计: ${passed}/${results.len} 通过')
if failed == 0 {
println('🎉 所有测试通过!FastCache 优化验证成功!')
} else {
println('⚠️ 有 ${failed} 个测试失败')
}
}
// 1. 基本缓存操作测试
fn test_basic_cache_operations() TestResult {
mut cache := hono.FastRouteCache.new(100)
// 测试 put 和 get
test_match := hono.ContextRouteMatch{
params: {'id': '123'}
path: '/users/:id'
}
cache.put('GET:/users/123', test_match)
if result := cache.get('GET:/users/123') {
if result.params['id'] or { '' } == '123' {
size, capacity := cache.get_stats()
return TestResult{
name: '基本缓存操作'
passed: true
detail: '缓存大小: ${size}/${capacity}'
}
}
}
return TestResult{
name: '基本缓存操作'
passed: false
detail: '缓存 get/put 失败'
}
}
// 2. 路由匹配正确性测试
fn test_route_matching_correctness() TestResult {
mut app := hono.Hono.new()
app.get('/users/:id', fn (mut c hono.Context) http.Response {
return c.text('user')
})
app.get('/posts/:post_id/comments/:comment_id', fn (mut c hono.Context) http.Response {
return c.text('comment')
})
mut router := app.fast_router
// 测试单参数路由
if match1 := router.match_route('GET', '/users/456') {
if match1.params['id'] or { '' } != '456' {
return TestResult{name: '路由匹配正确性', passed: false, detail: '单参数提取错误'}
}
} else {
return TestResult{name: '路由匹配正确性', passed: false, detail: '单参数路由匹配失败'}
}
// 测试多参数路由
if match2 := router.match_route('GET', '/posts/100/comments/200') {
post_id := match2.params['post_id'] or { '' }
comment_id := match2.params['comment_id'] or { '' }
if post_id != '100' || comment_id != '200' {
return TestResult{name: '路由匹配正确性', passed: false, detail: '多参数提取错误: post_id=${post_id}, comment_id=${comment_id}'}
}
} else {
return TestResult{name: '路由匹配正确性', passed: false, detail: '多参数路由匹配失败'}
}
return TestResult{name: '路由匹配正确性', passed: true, detail: '单参数和多参数路由均正确'}
}
// 3. 参数提取正确性测试
fn test_param_extraction() TestResult {
mut app := hono.Hono.new()
app.get('/api/:version/users/:user_id/posts/:post_id', fn (mut c hono.Context) http.Response {
return c.text('ok')
})
mut router := app.fast_router
test_cases := [
['/api/v1/users/100/posts/200', 'v1', '100', '200'],
['/api/v2/users/abc/posts/xyz', 'v2', 'abc', 'xyz'],
['/api/beta/users/user-123/posts/post-456', 'beta', 'user-123', 'post-456'],
]
for tc in test_cases {
path := tc[0]
expected_version := tc[1]
expected_user := tc[2]
expected_post := tc[3]
if match_result := router.match_route('GET', path) {
version := match_result.params['version'] or { '' }
user_id := match_result.params['user_id'] or { '' }
post_id := match_result.params['post_id'] or { '' }
if version != expected_version || user_id != expected_user || post_id != expected_post {
return TestResult{
name: '参数提取正确性'
passed: false
detail: '路径 ${path} 参数提取错误'
}
}
} else {
return TestResult{name: '参数提取正确性', passed: false, detail: '路径 ${path} 匹配失败'}
}
}
return TestResult{name: '参数提取正确性', passed: true, detail: '${test_cases.len} 个测试用例全部通过'}
}
// 4. 缓存命中测试
fn test_cache_hit() TestResult {
mut app := hono.Hono.new()
app.get('/users/:id', fn (mut c hono.Context) http.Response {
return c.text('user')
})
mut router := app.fast_router
// 第一次匹配(缓存未命中,需要正则匹配)
_ := router.match_route('GET', '/users/123')
// 获取缓存统计
cache_size1, _ := router.fast_cache.get_stats()
// 第二次匹配(应该命中缓存)
if match2 := router.match_route('GET', '/users/123') {
if match2.params['id'] or { '' } == '123' {
cache_size2, _ := router.fast_cache.get_stats()
return TestResult{
name: '缓存命中测试'
passed: true
detail: '缓存大小: ${cache_size1} -> ${cache_size2},参数正确'
}
}
}
return TestResult{name: '缓存命中测试', passed: false, detail: '缓存命中后参数错误'}
}
// 5. 缓存容量测试
fn test_cache_capacity() TestResult {
mut cache := hono.FastRouteCache.new(10) // 小容量测试
// 填满缓存
for i in 0 .. 10 {
cache.put('key${i}', hono.ContextRouteMatch{path: '/test/${i}'})
}
size1, _ := cache.get_stats()
if size1 != 10 {
return TestResult{name: '缓存容量测试', passed: false, detail: '填充后大小错误: ${size1}'}
}
// 超出容量,应该清空重建
cache.put('key_overflow', hono.ContextRouteMatch{path: '/overflow'})
size2, _ := cache.get_stats()
if size2 != 1 {
return TestResult{name: '缓存容量测试', passed: false, detail: '溢出后大小错误: ${size2}'}
}
// 验证新数据存在
if _ := cache.get('key_overflow') {
return TestResult{name: '缓存容量测试', passed: true, detail: '容量限制和清空重建正常'}
}
return TestResult{name: '缓存容量测试', passed: false, detail: '溢出后数据丢失'}
}
// 6. 多路由并发测试
fn test_multiple_routes() TestResult {
mut app := hono.Hono.new()
// 注册多个路由
app.get('/users/:id', fn (mut c hono.Context) http.Response { return c.text('user') })
app.get('/posts/:id', fn (mut c hono.Context) http.Response { return c.text('post') })
app.get('/comments/:id', fn (mut c hono.Context) http.Response { return c.text('comment') })
app.get('/tags/:name', fn (mut c hono.Context) http.Response { return c.text('tag') })
mut router := app.fast_router
// 交替匹配不同路由
test_paths := [
['/users/1', 'id', '1'],
['/posts/2', 'id', '2'],
['/comments/3', 'id', '3'],
['/tags/golang', 'name', 'golang'],
['/users/100', 'id', '100'],
['/posts/200', 'id', '200'],
]
for tc in test_paths {
path := tc[0]
param_name := tc[1]
expected_value := tc[2]
if match_result := router.match_route('GET', path) {
actual_value := match_result.params[param_name] or { '' }
if actual_value != expected_value {
return TestResult{
name: '多路由并发测试'
passed: false
detail: '路径 ${path} 参数错误: 期望 ${expected_value}, 实际 ${actual_value}'
}
}
} else {
return TestResult{name: '多路由并发测试', passed: false, detail: '路径 ${path} 匹配失败'}
}
}
return TestResult{name: '多路由并发测试', passed: true, detail: '${test_paths.len} 个路径全部正确'}
}
// 7. 性能基准测试
fn test_performance_benchmark() TestResult {
mut app := hono.Hono.new()
app.get('/users/:id', fn (mut c hono.Context) http.Response {
return c.text('user')
})
mut router := app.fast_router
// 预热
for i in 0 .. 100 {
_ := router.match_route('GET', '/users/${i}')
}
// 测试缓存命中性能
iterations := 10000
sw := time.new_stopwatch()
for _ in 0 .. iterations {
_ := router.match_route('GET', '/users/50') // 命中缓存
}
elapsed := sw.elapsed()
avg_ns := elapsed.nanoseconds() / iterations
avg_us := f64(avg_ns) / 1000.0
// 缓存命中应该 < 1μs
if avg_us < 1.0 {
return TestResult{
name: '性能基准测试'
passed: true
detail: '缓存命中平均耗时: ${avg_us:.3f}μs (< 1μs ✓)'
}
} else if avg_us < 5.0 {
return TestResult{
name: '性能基准测试'
passed: true
detail: '缓存命中平均耗时: ${avg_us:.3f}μs (< 5μs, 可接受)'
}
}
return TestResult{
name: '性能基准测试'
passed: false
detail: '缓存命中平均耗时: ${avg_us:.3f}μs (> 5μs, 过慢)'
}
}
// 8. 缓存一致性测试
fn test_cache_consistency() TestResult {
mut app := hono.Hono.new()
app.get('/items/:id', fn (mut c hono.Context) http.Response {
return c.text('item')
})
mut router := app.fast_router
// 多次匹配相同路径,验证结果一致
mut results := []string{}
for _ in 0 .. 100 {
if match_result := router.match_route('GET', '/items/999') {
results << match_result.params['id'] or { 'error' }
} else {
results << 'no_match'
}
}
// 检查所有结果是否一致
first := results[0]
for i, r in results {
if r != first {
return TestResult{
name: '缓存一致性测试'
passed: false
detail: '第 ${i} 次结果不一致: ${r} != ${first}'
}
}
}
if first == '999' {
return TestResult{name: '缓存一致性测试', passed: true, detail: '100 次匹配结果完全一致'}
}
return TestResult{name: '缓存一致性测试', passed: false, detail: '参数值错误: ${first}'}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+245
View File
@@ -0,0 +1,245 @@
// 高并发测试 (5000-10000 并发)
//
// 使用方法:
// 1. 启动服务器 (必须设置 ulimit): ulimit -n 65535 && ./bench_server_usockets
// 2. 运行测试: ulimit -n 65535 && go run v-hono/tests/test_high_concurrency.go
// 3. 单独测试某个级别: ulimit -n 65535 && go run v-hono/tests/test_high_concurrency.go 8000
//
// 重要提示:
// - 服务器和客户端都需要设置 ulimit -n 65535
// - 连续测试多个并发级别时,建议每次测试前重启服务器
// - TIME_WAIT 连接会影响后续测试,建议等待 10 秒后再测试下一个级别
//
// 系统配置要求 (macOS):
// sudo sysctl -w kern.ipc.somaxconn=8192
// ulimit -n 65535
package main
import (
"fmt"
"io"
"net/http"
"os"
"sort"
"strconv"
"sync"
"sync/atomic"
"time"
)
type BenchResult struct {
Concurrency int
TotalReqs int64
SuccessReqs int64
RPS float64
AvgLatency float64
P99Latency float64
SuccessRate float64
}
func main() {
baseURL := "http://127.0.0.1:8080/"
duration := 10 * time.Second
// 默认测试级别: 5000, 6000, 7000, 8000, 9000, 10000
concurrencyLevels := []int{5000, 6000, 7000, 8000, 9000, 10000}
// 支持命令行参数指定单个并发级别
if len(os.Args) > 1 {
level, err := strconv.Atoi(os.Args[1])
if err == nil {
concurrencyLevels = []int{level}
}
}
fmt.Println("╔═══════════════════════════════════════════════════════════════════════════╗")
fmt.Println("║ v-hono 高并发测试 (5000-10000 并发) ║")
fmt.Println("╚═══════════════════════════════════════════════════════════════════════════╝")
fmt.Println()
// 检查服务器是否运行
if !checkServer(baseURL) {
fmt.Println("❌ 服务器未运行")
fmt.Println(" 请先启动: ./bench_server_usockets")
fmt.Println()
fmt.Println(" 系统配置要求:")
fmt.Println(" - macOS: sudo sysctl -w kern.ipc.somaxconn=8192")
fmt.Println(" - ulimit -n 65535")
return
}
fmt.Println("✅ 服务器已就绪")
fmt.Println()
results := make([]BenchResult, 0, len(concurrencyLevels))
for _, conns := range concurrencyLevels {
result := runBenchmark(baseURL, conns, duration)
results = append(results, result)
// 测试间隔,让系统恢复 (TIME_WAIT 连接需要时间释放)
// macOS TIME_WAIT 默认 15-30 秒,建议等待 60 秒
if len(concurrencyLevels) > 1 {
fmt.Println(" ⏳ 等待 60 秒让系统恢复 (TIME_WAIT 连接释放)...")
time.Sleep(60 * time.Second)
}
}
// 输出汇总报告
printSummary(results)
}
func checkServer(baseURL string) bool {
client := &http.Client{Timeout: 2 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL)
if err == nil && resp.StatusCode < 400 {
resp.Body.Close()
return true
}
time.Sleep(200 * time.Millisecond)
}
return false
}
func runBenchmark(baseURL string, conns int, duration time.Duration) BenchResult {
fmt.Printf("🔥 测试 %d 并发连接 (持续 %v)\n", conns, duration)
var total, success int64
var totalLatencyNs int64
latencies := make([]int64, 0, 1000000)
var mu sync.Mutex
client := &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
MaxIdleConns: conns * 2,
MaxIdleConnsPerHost: conns * 2,
MaxConnsPerHost: 0,
IdleConnTimeout: 120 * time.Second,
DisableKeepAlives: false,
ForceAttemptHTTP2: false,
},
}
var wg sync.WaitGroup
stop := make(chan struct{})
start := time.Now()
// 同时启动所有连接
for i := 0; i < conns; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-stop:
return
default:
t0 := time.Now()
resp, err := client.Get(baseURL)
lat := time.Since(t0).Nanoseconds()
atomic.AddInt64(&total, 1)
atomic.AddInt64(&totalLatencyNs, lat)
mu.Lock()
latencies = append(latencies, lat)
mu.Unlock()
if err != nil {
continue
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
if resp.StatusCode < 400 {
atomic.AddInt64(&success, 1)
}
}
}
}()
}
time.Sleep(duration)
close(stop)
wg.Wait()
elapsed := time.Since(start)
// 计算 P99
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
p99 := int64(0)
if len(latencies) > 0 {
idx := len(latencies) * 99 / 100
p99 = latencies[idx]
}
avgLat := float64(totalLatencyNs) / float64(total) / 1e6
rps := float64(total) / elapsed.Seconds()
successRate := float64(success) / float64(total) * 100
// 判断测试结果
status := "✅"
if successRate < 99.0 {
status = "⚠️"
}
if successRate < 90.0 {
status = "❌"
}
fmt.Printf(" %s RPS: %8.0f Avg: %6.2fms P99: %6.2fms Success: %.1f%%\n",
status, rps, avgLat, float64(p99)/1e6, successRate)
fmt.Println()
return BenchResult{
Concurrency: conns,
TotalReqs: total,
SuccessReqs: success,
RPS: rps,
AvgLatency: avgLat,
P99Latency: float64(p99) / 1e6,
SuccessRate: successRate,
}
}
func printSummary(results []BenchResult) {
if len(results) <= 1 {
return
}
fmt.Println("═══════════════════════════════════════════════════════════════════════════")
fmt.Println(" 📊 测试结果汇总")
fmt.Println("═══════════════════════════════════════════════════════════════════════════")
fmt.Println()
fmt.Println("┌──────────────┬──────────────┬──────────────┬──────────────┬──────────────┐")
fmt.Println("│ 并发数 │ RPS │ 平均延迟 │ P99延迟 │ 成功率 │")
fmt.Println("├──────────────┼──────────────┼──────────────┼──────────────┼──────────────┤")
allPassed := true
for _, r := range results {
status := "✅"
if r.SuccessRate < 99.0 {
status = "⚠️"
allPassed = false
}
if r.SuccessRate < 90.0 {
status = "❌"
allPassed = false
}
fmt.Printf("│ %s %6d │ %10.0f │ %8.2fms │ %8.2fms │ %8.1f%% │\n",
status, r.Concurrency, r.RPS, r.AvgLatency, r.P99Latency, r.SuccessRate)
}
fmt.Println("└──────────────┴──────────────┴──────────────┴──────────────┴──────────────┘")
fmt.Println()
if allPassed {
fmt.Println("🎉 所有高并发测试通过!v-hono uSockets 后端表现优秀!")
} else {
fmt.Println("⚠️ 部分测试未达到 99% 成功率,请检查系统配置")
fmt.Println(" - macOS: sudo sysctl -w kern.ipc.somaxconn=8192")
fmt.Println(" - ulimit -n 65535")
}
fmt.Println()
}
+282
View File
@@ -0,0 +1,282 @@
module main
import time
// 测试 HTTP 解析优化
// 原始版本 - 使用 split 和 index
fn parse_path_and_query_original(full_path string) (string, map[string]string) {
mut query_map := map[string]string{}
if idx := full_path.index('?') {
path := full_path[..idx]
query_str := full_path[idx + 1..]
for part in query_str.split('&') {
if eq_idx := part.index('=') {
query_map[part[..eq_idx]] = part[eq_idx + 1..]
}
}
return path, query_map
}
return full_path, query_map
}
// 优化版本 - 零分配单次遍历
fn parse_path_and_query_optimized(full_path string) (string, map[string]string) {
mut query_map := map[string]string{}
len := full_path.len
if len == 0 {
return full_path, query_map
}
// 1. 查找 '?' 位置(单次遍历)
mut query_start := -1
for i in 0 .. len {
if full_path[i] == `?` {
query_start = i
break
}
}
// 没有查询参数,直接返回
if query_start == -1 {
return full_path, query_map
}
path := full_path[..query_start]
// 2. 解析查询参数(单次遍历,避免 split)
mut key_start := query_start + 1
mut key_end := -1
mut value_start := -1
for i := query_start + 1; i <= len; i++ {
ch := if i < len { full_path[i] } else { `&` } // 末尾视为分隔符
if ch == `=` && key_end == -1 {
key_end = i
value_start = i + 1
} else if ch == `&` {
// 完成一个键值对
if key_end > key_start && value_start > 0 {
key := full_path[key_start..key_end]
value := if value_start < i { full_path[value_start..i] } else { '' }
query_map[key] = value
} else if key_end == -1 && i > key_start {
// 只有 key 没有 value(如 ?foo&bar=1)
key := full_path[key_start..i]
query_map[key] = ''
}
// 重置状态
key_start = i + 1
key_end = -1
value_start = -1
}
}
return path, query_map
}
// Keep-Alive 检查 - 原始版本
fn check_keepalive_original(name string, value string) bool {
return name.to_lower() == 'connection' && value.to_lower().contains('keep-alive')
}
// 大小写不敏感比较
@[inline]
fn eq_ignore_case(a string, b string) bool {
if a.len != b.len {
return false
}
for i in 0 .. a.len {
ca := a[i]
cb := b[i]
la := if ca >= `A` && ca <= `Z` { ca + 32 } else { ca }
lb := if cb >= `A` && cb <= `Z` { cb + 32 } else { cb }
if la != lb {
return false
}
}
return true
}
// 大小写不敏感 contains
@[inline]
fn contains_ignore_case(haystack string, needle string) bool {
if needle.len > haystack.len {
return false
}
max_start := haystack.len - needle.len
for i := 0; i <= max_start; i++ {
mut found := true
for j in 0 .. needle.len {
ch := haystack[i + j]
cn := needle[j]
lh := if ch >= `A` && ch <= `Z` { ch + 32 } else { ch }
ln := if cn >= `A` && cn <= `Z` { cn + 32 } else { cn }
if lh != ln {
found = false
break
}
}
if found {
return true
}
}
return false
}
// Keep-Alive 检查 - 优化版本
fn check_keepalive_optimized(name string, value string) bool {
return name.len == 10 && eq_ignore_case(name, 'connection') && contains_ignore_case(value, 'keep-alive')
}
// 测试正确性
fn test_correctness() {
println('=== 测试正确性 ===')
test_cases := [
'/api/users',
'/api/users?id=123',
'/api/users?id=123&name=test',
'/api/users?id=123&name=test&active=true',
'/search?q=hello+world&page=1&limit=10',
'/path?empty=&key=value',
'/path?novalue&key=value',
'/',
'/?single=param',
]
mut all_passed := true
for tc in test_cases {
path_orig, query_orig := parse_path_and_query_original(tc)
path_opt, query_opt := parse_path_and_query_optimized(tc)
if path_orig != path_opt {
println('❌ 路径不匹配: ${tc}')
println(' 原始: ${path_orig}')
println(' 优化: ${path_opt}')
all_passed = false
} else if query_orig.len != query_opt.len {
println('❌ 查询参数数量不匹配: ${tc}')
println(' 原始: ${query_orig}')
println(' 优化: ${query_opt}')
all_passed = false
} else {
mut params_match := true
for k, v in query_orig {
if k !in query_opt || query_opt[k] != v {
params_match = false
break
}
}
if !params_match {
println('❌ 查询参数值不匹配: ${tc}')
println(' 原始: ${query_orig}')
println(' 优化: ${query_opt}')
all_passed = false
} else {
println('✓ ${tc}')
}
}
}
if all_passed {
println('\n✅ 所有正确性测试通过!')
} else {
println('\n❌ 部分测试失败')
}
}
// 性能基准测试
fn benchmark_performance() {
println('\n=== 性能基准测试 ===')
// 测试用例
test_paths := [
'/api/users', // 无查询参数
'/api/users?id=123', // 单个参数
'/api/users?id=123&name=test&active=true', // 多个参数
'/search?q=hello+world&page=1&limit=10&sort=desc&filter=active', // 复杂查询
]
iterations := 100000
for test_path in test_paths {
// 原始版本
sw_orig := time.new_stopwatch()
for _ in 0 .. iterations {
_, _ := parse_path_and_query_original(test_path)
}
time_orig := sw_orig.elapsed().microseconds()
// 优化版本
sw_opt := time.new_stopwatch()
for _ in 0 .. iterations {
_, _ := parse_path_and_query_optimized(test_path)
}
time_opt := sw_opt.elapsed().microseconds()
speedup := f64(time_orig) / f64(time_opt)
println('\n路径: ${test_path}')
println(' 原始版本: ${time_orig} μs (${iterations} 次)')
println(' 优化版本: ${time_opt} μs (${iterations} 次)')
println(' 提升: ${speedup:.2f}x')
}
}
// 测试 Keep-Alive 检查优化
fn test_keepalive_optimization() {
println('\n=== Keep-Alive 检查优化测试 ===')
test_cases := [
['Connection', 'keep-alive'],
['connection', 'Keep-Alive'],
['CONNECTION', 'KEEP-ALIVE'],
['Content-Type', 'application/json'],
['Connection', 'close'],
]
iterations := 100000
// 原始版本
sw_orig := time.new_stopwatch()
for _ in 0 .. iterations {
for tc in test_cases {
_ := check_keepalive_original(tc[0], tc[1])
}
}
time_orig := sw_orig.elapsed().microseconds()
// 优化版本
sw_opt := time.new_stopwatch()
for _ in 0 .. iterations {
for tc in test_cases {
_ := check_keepalive_optimized(tc[0], tc[1])
}
}
time_opt := sw_opt.elapsed().microseconds()
speedup := f64(time_orig) / f64(time_opt)
println('原始版本: ${time_orig} μs (${iterations * test_cases.len} 次检查)')
println('优化版本: ${time_opt} μs (${iterations * test_cases.len} 次检查)')
println('提升: ${speedup:.2f}x')
}
fn main() {
println('HTTP 解析优化测试')
println('=' .repeat(50))
test_correctness()
benchmark_performance()
test_keepalive_optimization()
println('\n' + '=' .repeat(50))
println('测试完成!')
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
import os
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
fn main() {
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
import time
+355
View File
@@ -0,0 +1,355 @@
// 中间件优化测试
// 测试三个优化点:
// 1. 零中间件快速路径
// 2. 中间件预计算(启动时排序)
// 3. 复用 cache key
import meiseayoung.hono
import time
import net.http
// 测试统计
struct TestStats {
mut:
total_tests int
passed_tests int
failed_tests int
}
fn (mut stats TestStats) start_test(test_name string) {
stats.total_tests++
print('🧪 ${test_name}... ')
}
fn (mut stats TestStats) pass_test() {
stats.passed_tests++
println('✅')
}
fn (mut stats TestStats) fail_test(error string) {
stats.failed_tests++
println('❌ ${error}')
}
fn (stats TestStats) print_summary() {
println('\n=== 测试总结 ===')
println('总测试数: ${stats.total_tests}')
println('通过: ${stats.passed_tests}')
println('失败: ${stats.failed_tests}')
if stats.failed_tests == 0 {
println('🎉 所有测试通过!')
} else {
println('⚠️ 有 ${stats.failed_tests} 个测试失败')
}
}
// 测试1:零中间件快速路径 - has_middlewares 标志
fn test_zero_middleware_flag(mut stats TestStats) {
stats.start_test('零中间件标志 (has_middlewares)')
mut app := hono.Hono.new()
// 新创建的应用应该没有中间件
if app.has_middlewares {
stats.fail_test('新应用不应该有中间件标志')
return
}
// 添加中间件后标志应该为 true
app.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
return next(mut c)
})
if !app.has_middlewares {
stats.fail_test('添加中间件后标志应该为 true')
return
}
stats.pass_test()
}
// 测试2:中间件预计算 - sorted_middleware_prefixes
fn test_middleware_precompute(mut stats TestStats) {
stats.start_test('中间件预计算 (sorted_middleware_prefixes)')
mut app := hono.Hono.new()
// 添加路由
app.get('/test', fn (mut c hono.Context) http.Response {
return c.text('test')
})
// 创建子应用并添加中间件
mut sub_app := hono.Hono.new()
sub_app.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
return next(mut c)
})
sub_app.get('/hello', fn (mut c hono.Context) http.Response {
return c.text('hello')
})
// 挂载子应用
app.route('/api', mut sub_app)
// 预计算前,sorted_middleware_prefixes 应该为空
if app.sorted_middleware_prefixes.len != 0 {
stats.fail_test('预计算前 sorted_middleware_prefixes 应该为空')
return
}
// 调用预计算
app.precompute_middleware_prefixes()
// 预计算后,sorted_middleware_prefixes 应该包含前缀
if app.sorted_middleware_prefixes.len == 0 && app.route_middlewares.len > 0 {
stats.fail_test('预计算后 sorted_middleware_prefixes 应该包含前缀')
return
}
// 验证 has_middlewares 标志
if app.route_middlewares.len > 0 && !app.has_middlewares {
stats.fail_test('有路由中间件时 has_middlewares 应该为 true')
return
}
stats.pass_test()
}
// 测试3:FastRouter cache key 复用
fn test_fast_router_cache_key_reuse(mut stats TestStats) {
stats.start_test('FastRouter cache key 复用')
mut router := hono.FastRouter.new()
// 添加静态路由
static_handler := hono.ContextHandler{
path: '/users'
handler: fn (mut c hono.Context) http.Response {
return c.text('users')
}
}
router.add_route('GET', static_handler, '') or {
stats.fail_test('添加静态路由失败')
return
}
// 添加动态路由
dynamic_handler := hono.ContextHandler{
path: '/users/:id'
handler: fn (mut c hono.Context) http.Response {
return c.text('user')
}
}
router.add_route('GET', dynamic_handler, '') or {
stats.fail_test('添加动态路由失败')
return
}
// 测试静态路由匹配
if _ := router.match_route('GET', '/users') {
// 成功
} else {
stats.fail_test('静态路由匹配失败')
return
}
// 测试动态路由匹配(第一次,会缓存)
if match1 := router.match_route('GET', '/users/123') {
if match1.params['id'] != '123' {
stats.fail_test('参数提取失败')
return
}
} else {
stats.fail_test('动态路由匹配失败')
return
}
// 测试动态路由匹配(第二次,应该命中缓存)
if match2 := router.match_route('GET', '/users/123') {
if match2.params['id'] != '123' {
stats.fail_test('缓存命中后参数提取失败')
return
}
} else {
stats.fail_test('缓存命中失败')
return
}
// 验证缓存状态
_, _, cache_count := router.get_stats()
if cache_count == 0 {
stats.fail_test('缓存应该有条目')
return
}
stats.pass_test()
}
// 测试4:HybridRouter cache key 复用
fn test_hybrid_router_cache_key_reuse(mut stats TestStats) {
stats.start_test('HybridRouter cache key 复用')
mut router := hono.ContextHybridRouter.new()
// 添加动态路由
dynamic_handler := hono.ContextHandler{
path: '/posts/:id'
handler: fn (mut c hono.Context) http.Response {
return c.text('post')
}
}
router.add_route('GET', dynamic_handler, '')
// 第一次匹配(无缓存)
if match1 := router.match_route('GET', '/posts/456') {
if match1.params['id'] != '456' {
stats.fail_test('参数提取失败')
return
}
} else {
stats.fail_test('动态路由匹配失败')
return
}
// 第二次匹配(应该命中缓存)
if match2 := router.match_route('GET', '/posts/456') {
if match2.params['id'] != '456' {
stats.fail_test('缓存命中后参数提取失败')
return
}
} else {
stats.fail_test('缓存命中失败')
return
}
stats.pass_test()
}
// 测试5:性能对比 - 有中间件 vs 无中间件
fn test_middleware_performance_comparison(mut stats TestStats) {
stats.start_test('中间件性能对比')
// 创建无中间件的路由器
mut router_no_mw := hono.FastRouter.new()
handler := hono.ContextHandler{
path: '/api/users/:id'
handler: fn (mut c hono.Context) http.Response {
return c.text('user')
}
}
router_no_mw.add_route('GET', handler, '') or {
stats.fail_test('添加路由失败')
return
}
// 预热
for _ in 0 .. 100 {
_ := router_no_mw.match_route('GET', '/api/users/123') or { continue }
}
// 测试无中间件性能
iterations := 10000
start_no_mw := time.now()
for _ in 0 .. iterations {
_ := router_no_mw.match_route('GET', '/api/users/123') or { continue }
}
duration_no_mw := time.since(start_no_mw)
// 创建有中间件的应用
mut app_with_mw := hono.Hono.new()
app_with_mw.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
return next(mut c)
})
app_with_mw.get('/api/users/:id', fn (mut c hono.Context) http.Response {
return c.text('user')
})
app_with_mw.precompute_middleware_prefixes()
// 预热
for _ in 0 .. 100 {
_ := app_with_mw.fast_router.match_route('GET', '/api/users/123') or { continue }
}
// 测试有中间件性能
start_with_mw := time.now()
for _ in 0 .. iterations {
_ := app_with_mw.fast_router.match_route('GET', '/api/users/123') or { continue }
}
duration_with_mw := time.since(start_with_mw)
println('')
println(' 📊 无中间件: ${duration_no_mw.milliseconds()}ms (${iterations} 次)')
println(' 📊 有中间件: ${duration_with_mw.milliseconds()}ms (${iterations} 次)')
// 性能差异不应该太大(路由匹配本身不受中间件影响)
stats.pass_test()
}
// 测试6:预计算排序正确性
fn test_precompute_sorting(mut stats TestStats) {
stats.start_test('预计算排序正确性')
mut app := hono.Hono.new()
// 添加多个子应用,模拟不同长度的前缀
mut sub1 := hono.Hono.new()
sub1.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
return next(mut c)
})
sub1.get('/test', fn (mut c hono.Context) http.Response {
return c.text('test')
})
mut sub2 := hono.Hono.new()
sub2.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
return next(mut c)
})
sub2.get('/test', fn (mut c hono.Context) http.Response {
return c.text('test')
})
mut sub3 := hono.Hono.new()
sub3.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
return next(mut c)
})
sub3.get('/test', fn (mut c hono.Context) http.Response {
return c.text('test')
})
// 按不同顺序挂载(长前缀先挂载)
app.route('/api/v1/users', mut sub1)
app.route('/api', mut sub2)
app.route('/api/v1', mut sub3)
// 预计算
app.precompute_middleware_prefixes()
// 验证排序:短前缀应该在前面
if app.sorted_middleware_prefixes.len >= 2 {
for i in 0 .. app.sorted_middleware_prefixes.len - 1 {
if app.sorted_middleware_prefixes[i].len > app.sorted_middleware_prefixes[i + 1].len {
stats.fail_test('前缀排序不正确:${app.sorted_middleware_prefixes[i]} 应该在 ${app.sorted_middleware_prefixes[i + 1]} 之后')
return
}
}
}
stats.pass_test()
}
fn main() {
println('🚀 开始中间件优化测试...\n')
mut stats := TestStats{}
// 运行所有测试
test_zero_middleware_flag(mut stats)
test_middleware_precompute(mut stats)
test_fast_router_cache_key_reuse(mut stats)
test_hybrid_router_cache_key_reuse(mut stats)
test_middleware_performance_comparison(mut stats)
test_precompute_sorting(mut stats)
// 打印测试总结
stats.print_summary()
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
BIN
View File
Binary file not shown.
+360
View File
@@ -0,0 +1,360 @@
// picoev 优化集成测试 (Go 版本)
// 测试 picoev 服务器的完整功能,确保优化没有引入新问题
//
// 使用方法:
// 1. 先启动测试服务器: v -enable-globals run v-hono/tests/test_picoev_server.v
// 2. 运行测试: go run v-hono/tests/test_picoev_integration.go
package main
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
const baseURL = "http://127.0.0.1:9999"
type TestStats struct {
total int
passed int
failed int
errors []string
}
func (s *TestStats) run(name string, testFn func() bool) {
s.total++
fmt.Printf(" 🧪 %s... ", name)
if testFn() {
s.passed++
fmt.Println("✅")
} else {
s.failed++
s.errors = append(s.errors, name)
fmt.Println("❌")
}
}
func (s *TestStats) summary() {
fmt.Println()
fmt.Println("═══════════════════════════════════════════════════════════════")
fmt.Printf("📊 测试结果: %d/%d 通过\n", s.passed, s.total)
if s.failed > 0 {
fmt.Println("❌ 失败的测试:")
for _, err := range s.errors {
fmt.Printf(" - %s\n", err)
}
} else {
fmt.Println("🎉 所有测试通过!picoev 优化验证成功!")
}
fmt.Println("═══════════════════════════════════════════════════════════════")
}
func main() {
fmt.Println("╔═══════════════════════════════════════════════════════════════╗")
fmt.Println("║ picoev 优化集成测试 (Go) ║")
fmt.Println("╚═══════════════════════════════════════════════════════════════╝")
fmt.Println()
// 验证服务器是否运行
fmt.Println("🔍 检查测试服务器...")
if !checkServerReady() {
fmt.Println("❌ 服务器未运行")
fmt.Println(" 请先启动: v -enable-globals run v-hono/tests/test_picoev_server.v")
return
}
fmt.Println("✅ 服务器已就绪")
fmt.Println()
stats := &TestStats{}
// 1. 基本 GET 路由测试
fmt.Println("📦 1. 基本 GET 路由测试")
stats.run("GET 根路径", testGetRoot)
stats.run("GET 健康检查", testGetHealth)
stats.run("GET 静态路由", testGetStatic)
fmt.Println()
// 2. 动态路由测试
fmt.Println("📦 2. 动态路由测试")
stats.run("单参数路由", testSingleParam)
stats.run("多参数路由", testMultiParams)
stats.run("嵌套参数路由", testNestedParams)
fmt.Println()
// 3. 查询参数测试
fmt.Println("📦 3. 查询参数测试")
stats.run("单个查询参数", testSingleQuery)
stats.run("多个查询参数", testMultiQuery)
fmt.Println()
// 4. 响应格式测试
fmt.Println("📦 4. 响应格式测试")
stats.run("JSON 响应", testJSONResponse)
stats.run("HTML 响应", testHTMLResponse)
stats.run("自定义状态码 201", testCustomStatus)
fmt.Println()
// 5. 中间件测试
fmt.Println("📦 5. 中间件测试")
stats.run("全局中间件响应头", testMiddlewareHeader)
fmt.Println()
// 6. 404 处理测试
fmt.Println("📦 6. 错误处理测试")
stats.run("404 未找到", testNotFound)
fmt.Println()
// 7. Keep-Alive 测试
fmt.Println("📦 7. Keep-Alive 连接测试")
stats.run("连接复用", testKeepAlive)
fmt.Println()
// 8. 性能测试
fmt.Println("📦 8. 性能测试")
stats.run("响应时间 < 50ms", testResponseTime)
stats.run("吞吐量测试", testThroughput)
fmt.Println()
// 9. 高并发基准测试
fmt.Println("📦 9. Keep-Alive 基准测试")
testBenchmark()
fmt.Println()
// 输出总结
stats.summary()
}
// 检查服务器是否就绪
func checkServerReady() bool {
client := &http.Client{Timeout: 2 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil && resp.StatusCode == 200 {
resp.Body.Close()
return true
}
time.Sleep(200 * time.Millisecond)
}
return false
}
// ==================== 基本 GET 路由测试 ====================
func testGetRoot() bool {
resp, body := doGet("/")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "Hello")
}
func testGetHealth() bool {
resp, body := doGet("/health")
return resp != nil && resp.StatusCode == 200 && body == "OK"
}
func testGetStatic() bool {
resp, body := doGet("/api/health")
return resp != nil && resp.StatusCode == 200 && body == "OK"
}
// ==================== 动态路由测试 ====================
func testSingleParam() bool {
resp, body := doGet("/api/users/456")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "456")
}
func testMultiParams() bool {
resp, body := doGet("/api/users/123/posts/789")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "123") && strings.Contains(body, "789")
}
func testNestedParams() bool {
resp, body := doGet("/api/categories/tech/items/laptop")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "tech") && strings.Contains(body, "laptop")
}
// ==================== 查询参数测试 ====================
func testSingleQuery() bool {
resp, body := doGet("/api/search?q=test")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "test")
}
func testMultiQuery() bool {
resp, body := doGet("/api/search?q=hello&limit=10&page=1")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "hello")
}
// ==================== 响应格式测试 ====================
func testJSONResponse() bool {
resp, _ := doGet("/api/json")
if resp == nil {
return false
}
contentType := resp.Header.Get("Content-Type")
return resp.StatusCode == 200 && strings.Contains(contentType, "application/json")
}
func testHTMLResponse() bool {
resp, _ := doGet("/api/html")
if resp == nil {
return false
}
contentType := resp.Header.Get("Content-Type")
return resp.StatusCode == 200 && strings.Contains(contentType, "text/html")
}
func testCustomStatus() bool {
resp, _ := doGet("/api/created")
return resp != nil && resp.StatusCode == 201
}
// ==================== 中间件测试 ====================
func testMiddlewareHeader() bool {
resp, body := doGet("/api/health")
// 检查中间件添加的响应头
if resp == nil {
return false
}
middlewareHeader := resp.Header.Get("X-Middleware")
return resp.StatusCode == 200 && body == "OK" && middlewareHeader == "applied"
}
// ==================== 错误处理测试 ====================
func testNotFound() bool {
resp, _ := doGet("/nonexistent/path/here")
return resp != nil && resp.StatusCode == 404
}
// ==================== Keep-Alive 测试 ====================
func testKeepAlive() bool {
// 使用同一个 transport 发送多个请求
transport := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableKeepAlives: false,
}
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL + "/api/health")
if err != nil || resp.StatusCode != 200 {
return false
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
return true
}
// ==================== 性能测试 ====================
func testResponseTime() bool {
client := &http.Client{Timeout: 5 * time.Second}
start := time.Now()
for i := 0; i < 10; i++ {
resp, err := client.Get(baseURL + "/api/health")
if err != nil {
return false
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
elapsed := time.Since(start)
avgMs := float64(elapsed.Milliseconds()) / 10.0
// 平均响应时间应小于 50ms
return avgMs < 50.0
}
func testThroughput() bool {
client := &http.Client{Timeout: 5 * time.Second}
requests := 50
success := 0
start := time.Now()
for i := 0; i < requests; i++ {
resp, err := client.Get(baseURL + "/api/health")
if err == nil && resp.StatusCode == 200 {
success++
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}
elapsed := time.Since(start)
rps := float64(success) * 1000.0 / float64(elapsed.Milliseconds())
fmt.Printf("(%.0f req/s) ", rps)
// 吞吐量应大于 20 req/s,成功率 > 90%
return rps > 20.0 && success >= requests*9/10
}
// Keep-Alive 基准测试
func testBenchmark() {
requests := 5000
conn, err := net.Dial("tcp", "127.0.0.1:9999")
if err != nil {
fmt.Println(" ❌ 连接失败:", err)
return
}
defer conn.Close()
// 预热
for i := 0; i < 100; i++ {
fmt.Fprintf(conn, "GET /health HTTP/1.1\r\nHost: 127.0.0.1:9999\r\nConnection: keep-alive\r\n\r\n")
buf := make([]byte, 256)
conn.Read(buf)
}
// 正式测试
start := time.Now()
success := 0
for i := 0; i < requests; i++ {
_, err := fmt.Fprintf(conn, "GET /health HTTP/1.1\r\nHost: 127.0.0.1:9999\r\nConnection: keep-alive\r\n\r\n")
if err != nil {
continue
}
buf := make([]byte, 256)
_, err = conn.Read(buf)
if err != nil {
continue
}
success++
}
elapsed := time.Since(start)
elapsedMs := float64(elapsed.Milliseconds())
rps := float64(success) * 1000.0 / elapsedMs
avgUs := elapsedMs * 1000.0 / float64(success)
fmt.Printf(" 成功请求: %d/%d\n", success, requests)
fmt.Printf(" 吞吐量: %.0f req/s\n", rps)
fmt.Printf(" 平均延迟: %.2fμs\n", avgUs)
}
// 辅助函数
func doGet(path string) (*http.Response, string) {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(baseURL + path)
if err != nil {
return nil, ""
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return resp, string(body)
}
-270
View File
@@ -1,270 +0,0 @@
// picoev 优化集成测试
// 测试 picoev 服务器的完整功能,确保优化没有引入新问题
//
// 使用方法:
// 1. 先启动测试服务器: v run tests/test_picoev_server.v
// 2. 运行测试: v run tests/test_picoev_integration.v
module main
import net.http
import time
// 测试统计
struct TestStats {
mut:
total int
passed int
failed int
errors []string
}
fn (mut s TestStats) run(name string, test_fn fn () bool) {
s.total++
print(' 🧪 ${name}... ')
result := test_fn()
if result {
s.passed++
println('✅')
} else {
s.failed++
s.errors << name
println('❌')
}
}
fn (s TestStats) summary() {
println('')
println('═══════════════════════════════════════════════════════════════')
println('📊 测试结果: ${s.passed}/${s.total} 通过')
if s.failed > 0 {
println('❌ 失败的测试:')
for err in s.errors {
println(' - ${err}')
}
} else {
println('🎉 所有测试通过!picoev 优化验证成功!')
}
println('═══════════════════════════════════════════════════════════════')
}
const base_url = 'http://127.0.0.1:9999'
fn main() {
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ picoev 优化集成测试 ║')
println('╚═══════════════════════════════════════════════════════════════╝')
println('')
// 验证服务器是否运行
println('🔍 检查测试服务器...')
if !check_server_ready() {
println('❌ 服务器未运行')
println(' 请先启动: v run tests/test_picoev_server.v')
return
}
println('✅ 服务器已就绪')
println('')
mut stats := TestStats{}
// 1. 基本 GET 路由测试
println('📦 1. 基本 GET 路由测试')
stats.run('GET 根路径', test_get_root)
stats.run('GET 健康检查', test_get_health)
stats.run('GET 静态路由', test_get_static)
println('')
// 2. 动态路由测试
println('📦 2. 动态路由测试')
stats.run('单参数路由', test_single_param)
stats.run('多参数路由', test_multi_params)
stats.run('嵌套参数路由', test_nested_params)
println('')
// 3. 查询参数测试
println('📦 3. 查询参数测试')
stats.run('单个查询参数', test_single_query)
stats.run('多个查询参数', test_multi_query)
println('')
// 4. 响应格式测试
println('📦 4. 响应格式测试')
stats.run('JSON 响应', test_json_response)
stats.run('HTML 响应', test_html_response)
stats.run('自定义状态码 201', test_custom_status)
println('')
// 5. 中间件测试
println('📦 5. 中间件测试')
stats.run('全局中间件响应头', test_middleware_header)
println('')
// 6. 404 处理测试
println('📦 6. 错误处理测试')
stats.run('404 未找到', test_not_found)
println('')
// 7. Keep-Alive 测试
println('📦 7. Keep-Alive 连接测试')
stats.run('连接复用', test_keep_alive)
println('')
// 8. 性能测试
println('📦 8. 性能测试')
stats.run('响应时间 < 50ms', test_response_time)
stats.run('吞吐量测试', test_throughput)
println('')
// 输出总结
stats.summary()
}
// 检查服务器是否就绪
fn check_server_ready() bool {
for _ in 0 .. 5 {
resp := http.get(base_url + '/health') or {
time.sleep(200 * time.millisecond)
continue
}
if resp.status_code == 200 {
return true
}
time.sleep(200 * time.millisecond)
}
return false
}
// ==================== 基本 GET 路由测试 ====================
fn test_get_root() bool {
resp := http.get(base_url + '/') or { return false }
return resp.status_code == 200 && resp.body.contains('Hello')
}
fn test_get_health() bool {
resp := http.get(base_url + '/health') or { return false }
return resp.status_code == 200 && resp.body == 'OK'
}
fn test_get_static() bool {
resp := http.get(base_url + '/api/health') or { return false }
return resp.status_code == 200 && resp.body == 'OK'
}
// ==================== 动态路由测试 ====================
fn test_single_param() bool {
resp := http.get(base_url + '/api/users/456') or { return false }
return resp.status_code == 200 && resp.body.contains('456')
}
fn test_multi_params() bool {
resp := http.get(base_url + '/api/users/123/posts/789') or { return false }
return resp.status_code == 200 && resp.body.contains('123') && resp.body.contains('789')
}
fn test_nested_params() bool {
resp := http.get(base_url + '/api/categories/tech/items/laptop') or { return false }
return resp.status_code == 200 && resp.body.contains('tech') && resp.body.contains('laptop')
}
// ==================== 查询参数测试 ====================
fn test_single_query() bool {
resp := http.get(base_url + '/api/search?q=test') or { return false }
return resp.status_code == 200 && resp.body.contains('test')
}
fn test_multi_query() bool {
resp := http.get(base_url + '/api/search?q=hello&limit=10&page=1') or { return false }
return resp.status_code == 200 && resp.body.contains('hello')
}
// ==================== 响应格式测试 ====================
fn test_json_response() bool {
resp := http.get(base_url + '/api/json') or { return false }
content_type := resp.header.get(.content_type) or { '' }
return resp.status_code == 200 && content_type.contains('application/json')
}
fn test_html_response() bool {
resp := http.get(base_url + '/api/html') or { return false }
content_type := resp.header.get(.content_type) or { '' }
return resp.status_code == 200 && content_type.contains('text/html')
}
fn test_custom_status() bool {
resp := http.get(base_url + '/api/created') or { return false }
return resp.status_code == 201
}
// ==================== 中间件测试 ====================
fn test_middleware_header() bool {
resp := http.get(base_url + '/api/health') or { return false }
// 检查中间件添加的响应头 - 通过原始响应检查
raw_resp := resp.body
// 中间件应该已经执行,检查响应是否正常
return resp.status_code == 200 && raw_resp == 'OK'
}
// ==================== 错误处理测试 ====================
fn test_not_found() bool {
resp := http.get(base_url + '/nonexistent/path/here') or { return false }
return resp.status_code == 404
}
// ==================== Keep-Alive 测试 ====================
fn test_keep_alive() bool {
// 发送多个请求,检查连接是否正常
for _ in 0 .. 5 {
resp := http.get(base_url + '/api/health') or { return false }
if resp.status_code != 200 {
return false
}
}
return true
}
// ==================== 性能测试 ====================
fn test_response_time() bool {
sw := time.new_stopwatch()
for _ in 0 .. 10 {
_ := http.get(base_url + '/api/health') or { return false }
}
elapsed := sw.elapsed()
avg_ms := f64(elapsed.milliseconds()) / 10.0
// 平均响应时间应小于 50ms
return avg_ms < 50.0
}
fn test_throughput() bool {
sw := time.new_stopwatch()
requests := 50
mut success := 0
for _ in 0 .. requests {
resp := http.get(base_url + '/api/health') or { continue }
if resp.status_code == 200 {
success++
}
}
elapsed := sw.elapsed()
rps := f64(success) * 1000.0 / f64(elapsed.milliseconds())
print('(${rps:.0f} req/s) ')
// 吞吐量应大于 20 req/s,成功率 > 90%
return rps > 20.0 && success >= requests * 9 / 10
}
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -3,7 +3,7 @@
module main
import hono
import meiseayoung.hono
import net.http
fn main() {
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
// 重定向功能测试
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
import regex
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
import regex
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
fn main() {
println('=== 测试输入验证和路径安全 ===')
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
// 简化的测试统计
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
import time
import strings
+268
View File
@@ -0,0 +1,268 @@
// uSockets 集成测试 (Go 版本)
//
// 使用方法:
// 1. 先启动测试服务器: v -enable-globals run v-hono/tests/test_usockets_server.v
// 2. 运行测试: go run v-hono/tests/test_usockets_integration.go
package main
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
const baseURL = "http://127.0.0.1:9998"
type TestStats struct {
total int
passed int
failed int
errors []string
}
func (s *TestStats) run(name string, testFn func() bool) {
s.total++
fmt.Printf(" 🧪 %s... ", name)
if testFn() {
s.passed++
fmt.Println("✅")
} else {
s.failed++
s.errors = append(s.errors, name)
fmt.Println("❌")
}
}
func (s *TestStats) summary() {
fmt.Println()
fmt.Println("═══════════════════════════════════════════════════════════════")
fmt.Printf("📊 测试结果: %d/%d 通过\n", s.passed, s.total)
if s.failed > 0 {
fmt.Println("❌ 失败的测试:")
for _, err := range s.errors {
fmt.Printf(" - %s\n", err)
}
} else {
fmt.Println("🎉 所有测试通过!uSockets 后端验证成功!")
}
fmt.Println("═══════════════════════════════════════════════════════════════")
}
func main() {
fmt.Println("╔═══════════════════════════════════════════════════════════════╗")
fmt.Println("║ uSockets 集成测试 (Go) ║")
fmt.Println("╚═══════════════════════════════════════════════════════════════╝")
fmt.Println()
// 验证服务器是否运行
fmt.Println("🔍 检查 uSockets 测试服务器...")
if !checkServerReady() {
fmt.Println("❌ 服务器未运行")
fmt.Println(" 请先启动: v -enable-globals run v-hono/tests/test_usockets_server.v")
return
}
fmt.Println("✅ 服务器已就绪")
fmt.Println()
stats := &TestStats{}
// 1. 基本路由测试
fmt.Println("📦 1. 基本路由测试")
stats.run("GET /", testGetRoot)
stats.run("GET /health", testGetHealth)
fmt.Println()
// 2. JSON 响应测试
fmt.Println("📦 2. JSON 响应测试")
stats.run("GET /api/json", testJSONResponse)
fmt.Println()
// 3. 动态路由测试
fmt.Println("📦 3. 动态路由测试")
stats.run("GET /api/users/:id", testSingleParam)
stats.run("GET /api/users/:user_id/posts/:post_id", testMultiParams)
fmt.Println()
// 4. 查询参数测试
fmt.Println("📦 4. 查询参数测试")
stats.run("GET /api/search?q=hello", testQueryParam)
fmt.Println()
// 5. 404 测试
fmt.Println("📦 5. 404 测试")
stats.run("404 Not Found", testNotFound)
fmt.Println()
// 6. Keep-Alive 测试
fmt.Println("📦 6. Keep-Alive 连接测试")
stats.run("Keep-Alive 连接复用", testKeepAlive)
fmt.Println()
// 7. 性能测试
fmt.Println("📦 7. 性能测试")
stats.run("吞吐量测试", testThroughput)
fmt.Println()
// 8. 高并发基准测试
fmt.Println("📦 8. Keep-Alive 基准测试")
testBenchmark()
fmt.Println()
// 输出总结
stats.summary()
}
func checkServerReady() bool {
client := &http.Client{Timeout: 2 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil && resp.StatusCode == 200 {
resp.Body.Close()
return true
}
time.Sleep(200 * time.Millisecond)
}
return false
}
func testGetRoot() bool {
resp, body := doGet("/")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "Hello from uSockets")
}
func testGetHealth() bool {
resp, body := doGet("/health")
return resp != nil && resp.StatusCode == 200 && body == "OK"
}
func testJSONResponse() bool {
resp, body := doGet("/api/json")
if resp == nil {
return false
}
contentType := resp.Header.Get("Content-Type")
return resp.StatusCode == 200 && strings.Contains(contentType, "application/json") && strings.Contains(body, "Hello JSON")
}
func testSingleParam() bool {
resp, body := doGet("/api/users/123")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "123")
}
func testMultiParams() bool {
resp, body := doGet("/api/users/100/posts/200")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "100") && strings.Contains(body, "200")
}
func testQueryParam() bool {
resp, body := doGet("/api/search?q=hello")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "hello")
}
func testNotFound() bool {
resp, _ := doGet("/nonexistent")
return resp != nil && resp.StatusCode == 404
}
func testKeepAlive() bool {
transport := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableKeepAlives: false,
}
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL + "/health")
if err != nil || resp.StatusCode != 200 {
return false
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
return true
}
func testThroughput() bool {
client := &http.Client{Timeout: 5 * time.Second}
requests := 100
success := 0
start := time.Now()
for i := 0; i < requests; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil && resp.StatusCode == 200 {
success++
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}
elapsed := time.Since(start)
rps := float64(success) * 1000.0 / float64(elapsed.Milliseconds())
fmt.Printf("(%.0f req/s) ", rps)
return success >= requests*9/10
}
func testBenchmark() {
requests := 5000
conn, err := net.Dial("tcp", "127.0.0.1:9998")
if err != nil {
fmt.Println(" ❌ 连接失败:", err)
return
}
defer conn.Close()
// 预热
for i := 0; i < 100; i++ {
fmt.Fprintf(conn, "GET /health HTTP/1.1\r\nHost: 127.0.0.1:9998\r\nConnection: keep-alive\r\n\r\n")
buf := make([]byte, 256)
conn.Read(buf)
}
// 正式测试
start := time.Now()
success := 0
for i := 0; i < requests; i++ {
_, err := fmt.Fprintf(conn, "GET /health HTTP/1.1\r\nHost: 127.0.0.1:9998\r\nConnection: keep-alive\r\n\r\n")
if err != nil {
continue
}
buf := make([]byte, 256)
_, err = conn.Read(buf)
if err != nil {
continue
}
success++
}
elapsed := time.Since(start)
elapsedMs := float64(elapsed.Milliseconds())
rps := float64(success) * 1000.0 / elapsedMs
avgUs := elapsedMs * 1000.0 / float64(success)
fmt.Printf(" 成功请求: %d/%d\n", success, requests)
fmt.Printf(" 吞吐量: %.0f req/s\n", rps)
fmt.Printf(" 平均延迟: %.2fμs\n", avgUs)
}
func doGet(path string) (*http.Response, string) {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(baseURL + path)
if err != nil {
return nil, ""
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return resp, string(body)
}
+50
View File
@@ -0,0 +1,50 @@
// uSockets 测试服务器
module main
import net.http
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
// 基本路由
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello from uSockets!')
})
app.get('/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
// JSON 响应
app.get('/api/json', fn (mut c hono.Context) http.Response {
return c.json('{"message": "Hello JSON"}')
})
// 动态路由
app.get('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}"}')
})
app.get('/api/users/:user_id/posts/:post_id', fn (mut c hono.Context) http.Response {
user_id := c.params['user_id'] or { '' }
post_id := c.params['post_id'] or { '' }
return c.json('{"user_id": "${user_id}", "post_id": "${post_id}"}')
})
// 查询参数
app.get('/api/search', fn (mut c hono.Context) http.Response {
q := c.query['q'] or { '' }
return c.json('{"query": "${q}"}')
})
// 404 处理
app.not_found(fn (mut c hono.Context) http.Response {
c.status(404)
return c.json('{"error": "Not Found"}')
})
println('[usockets-test-server] Starting on port 9998...')
app.listen_usockets(9998)
}
+44
View File
@@ -0,0 +1,44 @@
// uSockets 简化测试服务器 - 与外层 main.v 配置一致
module main
import meiseayoung.hono
import net.http
import x.json2
// JSON 响应结构体
struct JsonResponse {
message string
}
struct UserResponse {
user_id string
}
fn main() {
mut app := hono.Hono.new()
// 与外层 main.v 完全一致的路由配置(无中间件)
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello, World!')
})
app.get('/json', fn (mut c hono.Context) http.Response {
data := JsonResponse{message: 'Hello, JSON!'}
json_str := json2.encode(data)
return c.json(json_str)
})
app.get('/users/:id', fn (mut c hono.Context) http.Response {
user_id := c.params['id'] or { 'unknown' }
data := UserResponse{user_id: user_id}
json_str := json2.encode(data)
return c.json(json_str)
})
app.get('/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
println('[usockets-simple] Starting on port 9999 (uSockets)...')
app.listen_usockets(9999)
}
+27 -2
View File
@@ -2,6 +2,31 @@
High-performance server backend using [uSockets](https://github.com/uNetworking/uSockets) library.
## High Concurrency Performance
The included `libusockets_full.a` has been optimized with **backlog=16384** to support high concurrency:
| Concurrent | RPS | Success Rate |
|------------|-----|--------------|
| 4,000 | 112,614 | 100% |
| 6,000 | 56,728 | 100% |
| 8,000 | 33,255 | 100% |
| 10,000 | 25,964 | 100% |
### System Requirements
For 10,000+ concurrent connections:
```bash
# macOS
sudo sysctl -w kern.ipc.somaxconn=8192
ulimit -n 65535
# Linux
sudo sysctl -w net.core.somaxconn=8192
ulimit -n 65535
```
## Performance
Based on benchmark tests (200 connections, 100K requests):
@@ -16,7 +41,7 @@ Based on benchmark tests (200 connections, 100K requests):
## Usage
```v
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -74,7 +99,7 @@ usockets/
```v
// Custom configuration
app.listen_usockets_with_config(hono.UsocketsConfig{
app.listen_usockets_with_config(meiseayoung.hono.UsocketsConfig{
port: 8080
host: '0.0.0.0'
keepalive_timeout: 30
+55
View File
@@ -0,0 +1,55 @@
#!/bin/bash
# uSockets 编译脚本
# 用于重新编译 libusockets_full.a
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
USOCKETS_DIR="/tmp/uSockets"
echo "=== uSockets 编译脚本 ==="
# 检查是否有 uSockets 源码
if [ ! -d "$USOCKETS_DIR" ]; then
echo "克隆 uSockets..."
git clone --depth 1 https://github.com/uNetworking/uSockets.git "$USOCKETS_DIR"
fi
# 应用 backlog 修改
echo "应用 backlog=16384 修改..."
if [ -f "$SCRIPT_DIR/src/bsd.c" ]; then
cp "$SCRIPT_DIR/src/bsd.c" "$USOCKETS_DIR/src/bsd.c"
else
# 如果没有本地修改的源码,直接修改
sed -i.bak 's/listen(listenFd, 512)/listen(listenFd, 16384)/g' "$USOCKETS_DIR/src/bsd.c"
fi
# 编译
echo "编译 uSockets..."
cd "$USOCKETS_DIR"
make clean
# 根据系统选择编译参数
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS
if [[ $(uname -m) == "arm64" ]]; then
# Apple Silicon
WITH_LIBUV=1 CFLAGS="-I/opt/homebrew/include" make
else
# Intel Mac
WITH_LIBUV=1 CFLAGS="-I/usr/local/include" make
fi
else
# Linux
WITH_LIBUV=1 make
fi
# 复制到 v-hono
echo "复制库文件..."
cp "$USOCKETS_DIR/uSockets.a" "$SCRIPT_DIR/../lib/libusockets_full.a"
echo "=== 编译完成 ==="
echo "库文件: $SCRIPT_DIR/../lib/libusockets_full.a"
echo ""
echo "重新编译 v-hono 应用:"
echo " v -enable-globals -prod -o your_app your_app.v"
+767
View File
@@ -0,0 +1,767 @@
/*
* Authored by Alex Hultman, 2018-2021.
* Intellectual property of third-party.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Todo: this file should lie in networking/bsd.c */
#define __APPLE_USE_RFC_3542
#include "libusockets.h"
#include "internal/internal.h"
#include <stdio.h>
#include <stdlib.h>
#ifndef _WIN32
//#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#endif
/* Internal structure of packet buffer */
struct us_internal_udp_packet_buffer {
#if defined(_WIN32) || defined(__APPLE__)
char *buf[LIBUS_UDP_MAX_NUM];
size_t len[LIBUS_UDP_MAX_NUM];
struct sockaddr_storage addr[LIBUS_UDP_MAX_NUM];
#else
struct mmsghdr msgvec[LIBUS_UDP_MAX_NUM];
struct iovec iov[LIBUS_UDP_MAX_NUM];
struct sockaddr_storage addr[LIBUS_UDP_MAX_NUM];
char control[LIBUS_UDP_MAX_NUM][256];
#endif
};
/* We need to emulate sendmmsg, recvmmsg on platform who don't have it */
int bsd_sendmmsg(LIBUS_SOCKET_DESCRIPTOR fd, void *msgvec, unsigned int vlen, int flags) {
#if defined(__APPLE__)
struct mmsghdr {
struct msghdr msg_hdr; /* Message header */
unsigned int msg_len; /* Number of bytes transmitted */
};
struct mmsghdr *hdrs = (struct mmsghdr *) msgvec;
for (int i = 0; i < vlen; i++) {
int ret = sendmsg(fd, &hdrs[i].msg_hdr, flags);
if (ret == -1) {
if (i) {
return i;
} else {
return -1;
}
} else {
hdrs[i].msg_len = ret;
}
}
return vlen;
#elif defined(_WIN32)
struct us_internal_udp_packet_buffer *packet_buffer = (struct us_internal_udp_packet_buffer *) msgvec;
/* Let's just use sendto here */
/* Winsock does not have sendmsg, while macOS has, however, we simply use sendto since both macOS and Winsock has it.
* Besides, you should use Linux either way to get best performance with the sendmmsg */
// while we do not get error, send next
for (int i = 0; i < LIBUS_UDP_MAX_NUM; i++) {
// need to support ipv6 addresses also!
int ret = sendto(fd, packet_buffer->buf[i], packet_buffer->len[i], flags, (struct sockaddr *)&packet_buffer->addr[i], sizeof(struct sockaddr_in));
if (ret == -1) {
// if we fail then we need to buffer up, no that's not our problem
// we do need to register poll out though and have a callback for it
return i;
}
//printf("sendto: %d\n", ret);
}
return LIBUS_UDP_MAX_NUM; // one message
#else
return sendmmsg(fd, (struct mmsghdr *)msgvec, vlen, flags | MSG_NOSIGNAL);
#endif
}
int bsd_recvmmsg(LIBUS_SOCKET_DESCRIPTOR fd, void *msgvec, unsigned int vlen, int flags, void *timeout) {
#if defined(_WIN32) || defined(__APPLE__)
struct us_internal_udp_packet_buffer *packet_buffer = (struct us_internal_udp_packet_buffer *) msgvec;
for (int i = 0; i < LIBUS_UDP_MAX_NUM; i++) {
socklen_t addr_len = sizeof(struct sockaddr_storage);
int ret = recvfrom(fd, packet_buffer->buf[i], LIBUS_UDP_MAX_SIZE, flags, (struct sockaddr *)&packet_buffer->addr[i], &addr_len);
if (ret == -1) {
return i;
}
packet_buffer->len[i] = ret;
}
return LIBUS_UDP_MAX_NUM;
#else
// we need to set controllen for ip packet
for (int i = 0; i < vlen; i++) {
((struct mmsghdr *)msgvec)[i].msg_hdr.msg_controllen = 256;
}
return recvmmsg(fd, (struct mmsghdr *)msgvec, vlen, flags, 0);
#endif
}
// this one is needed for knowing the destination addr of udp packet
// an udp socket can only bind to one port, and that port never changes
// this function returns ONLY the IP address, not any port
int bsd_udp_packet_buffer_local_ip(void *msgvec, int index, char *ip) {
#if defined(_WIN32) || defined(__APPLE__)
return 0; // not supported
#else
struct msghdr *mh = &((struct mmsghdr *) msgvec)[index].msg_hdr;
for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(mh); cmsg != NULL; cmsg = CMSG_NXTHDR(mh, cmsg)) {
// Linux ipv4
#ifdef IP_PKTINFO
if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO) {
struct in_pktinfo *pi = (struct in_pktinfo *) CMSG_DATA(cmsg);
memcpy(ip, &pi->ipi_addr, 4);
return 4;
}
// FreeBSD ipv4
#elif IP_RECVDSTADDR
if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR) {
struct in_addr *addr = (struct in_addr *) CMSG_DATA(cmsg);
memcpy(ip, addr, 4);
return 4;
}
#endif
// Linux, FreeBSD ipv6
if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
struct in6_pktinfo *pi6 = (struct in6_pktinfo *) CMSG_DATA(cmsg);
memcpy(ip, &pi6->ipi6_addr, 16);
return 16;
}
}
return 0; // no length
#endif
}
char *bsd_udp_packet_buffer_peer(void *msgvec, int index) {
#if defined(_WIN32) || defined(__APPLE__)
struct us_internal_udp_packet_buffer *packet_buffer = (struct us_internal_udp_packet_buffer *) msgvec;
return (char *)&packet_buffer->addr[index];
#else
return ((struct mmsghdr *) msgvec)[index].msg_hdr.msg_name;
#endif
}
char *bsd_udp_packet_buffer_payload(void *msgvec, int index) {
#if defined(_WIN32) || defined(__APPLE__)
struct us_internal_udp_packet_buffer *packet_buffer = (struct us_internal_udp_packet_buffer *) msgvec;
return packet_buffer->buf[index];
#else
return ((struct mmsghdr *) msgvec)[index].msg_hdr.msg_iov[0].iov_base;
#endif
}
int bsd_udp_packet_buffer_payload_length(void *msgvec, int index) {
#if defined(_WIN32) || defined(__APPLE__)
struct us_internal_udp_packet_buffer *packet_buffer = (struct us_internal_udp_packet_buffer *) msgvec;
return packet_buffer->len[index];
#else
return ((struct mmsghdr *) msgvec)[index].msg_len;
#endif
}
void bsd_udp_buffer_set_packet_payload(struct us_udp_packet_buffer_t *send_buf, int index, int offset, void *payload, int length, void *peer_addr) {
#if defined(_WIN32) || defined(__APPLE__)
struct us_internal_udp_packet_buffer *packet_buffer = (struct us_internal_udp_packet_buffer *) send_buf;
memcpy(packet_buffer->buf[index], payload, length);
memcpy(&packet_buffer->addr[index], peer_addr, sizeof(struct sockaddr_storage));
packet_buffer->len[index] = length;
#else
//printf("length: %d, offset: %d\n", length, offset);
struct mmsghdr *ss = (struct mmsghdr *) send_buf;
// copy the peer address
memcpy(ss[index].msg_hdr.msg_name, peer_addr, /*ss[index].msg_hdr.msg_namelen*/ sizeof(struct sockaddr_in));
// set control length to 0
ss[index].msg_hdr.msg_controllen = 0;
// copy the payload
ss[index].msg_hdr.msg_iov->iov_len = length + offset;
memcpy(((char *) ss[index].msg_hdr.msg_iov->iov_base) + offset, payload, length);
#endif
}
/* The maximum UDP payload size is 64kb, but in IPV6 you can have jumbopackets larger than so.
* We do not support those jumbo packets currently, but will safely ignore them.
* Any sane sender would assume we don't support them if we consistently drop them.
* Therefore a udp_packet_buffer_t will be 64 MB in size (64kb * 1024). */
void *bsd_create_udp_packet_buffer() {
#if defined(_WIN32) || defined(__APPLE__)
struct us_internal_udp_packet_buffer *b = malloc(sizeof(struct us_internal_udp_packet_buffer) + LIBUS_UDP_MAX_SIZE * LIBUS_UDP_MAX_NUM);
for (int i = 0; i < LIBUS_UDP_MAX_NUM; i++) {
b->buf[i] = ((char *) b) + sizeof(struct us_internal_udp_packet_buffer) + LIBUS_UDP_MAX_SIZE * i;
}
return (struct us_udp_packet_buffer_t *) b;
#else
/* Allocate 64kb times 1024 */
struct us_internal_udp_packet_buffer *b = malloc(sizeof(struct us_internal_udp_packet_buffer) + LIBUS_UDP_MAX_SIZE * LIBUS_UDP_MAX_NUM);
for (int n = 0; n < LIBUS_UDP_MAX_NUM; ++n) {
b->iov[n].iov_base = &((char *) (b + 1))[n * LIBUS_UDP_MAX_SIZE];
b->iov[n].iov_len = LIBUS_UDP_MAX_SIZE;
b->msgvec[n].msg_hdr = (struct msghdr) {
.msg_name = &b->addr[n],
.msg_namelen = sizeof (struct sockaddr_storage),
.msg_iov = &b->iov[n],
.msg_iovlen = 1,
.msg_control = b->control[n],
.msg_controllen = 256,
};
}
return (struct us_udp_packet_buffer_t *) b;
#endif
}
LIBUS_SOCKET_DESCRIPTOR apple_no_sigpipe(LIBUS_SOCKET_DESCRIPTOR fd) {
#ifdef __APPLE__
if (fd != LIBUS_SOCKET_ERROR) {
int no_sigpipe = 1;
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void *) &no_sigpipe, sizeof(int));
}
#endif
return fd;
}
LIBUS_SOCKET_DESCRIPTOR bsd_set_nonblocking(LIBUS_SOCKET_DESCRIPTOR fd) {
#ifdef _WIN32
/* Libuv will set windows sockets as non-blocking */
#else
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
#endif
return fd;
}
void bsd_socket_nodelay(LIBUS_SOCKET_DESCRIPTOR fd, int enabled) {
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void *) &enabled, sizeof(enabled));
}
void bsd_socket_flush(LIBUS_SOCKET_DESCRIPTOR fd) {
// Linux TCP_CORK has the same underlying corking mechanism as with MSG_MORE
#ifdef TCP_CORK
int enabled = 0;
setsockopt(fd, IPPROTO_TCP, TCP_CORK, (void *) &enabled, sizeof(int));
#endif
}
LIBUS_SOCKET_DESCRIPTOR bsd_create_socket(int domain, int type, int protocol) {
// returns INVALID_SOCKET on error
int flags = 0;
#if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
flags = SOCK_CLOEXEC | SOCK_NONBLOCK;
#endif
LIBUS_SOCKET_DESCRIPTOR created_fd = socket(domain, type | flags, protocol);
return bsd_set_nonblocking(apple_no_sigpipe(created_fd));
}
void bsd_close_socket(LIBUS_SOCKET_DESCRIPTOR fd) {
#ifdef _WIN32
closesocket(fd);
#else
close(fd);
#endif
}
void bsd_shutdown_socket(LIBUS_SOCKET_DESCRIPTOR fd) {
#ifdef _WIN32
shutdown(fd, SD_SEND);
#else
shutdown(fd, SHUT_WR);
#endif
}
void bsd_shutdown_socket_read(LIBUS_SOCKET_DESCRIPTOR fd) {
#ifdef _WIN32
shutdown(fd, SD_RECEIVE);
#else
shutdown(fd, SHUT_RD);
#endif
}
void internal_finalize_bsd_addr(struct bsd_addr_t *addr) {
// parse, so to speak, the address
if (addr->mem.ss_family == AF_INET6) {
addr->ip = (char *) &((struct sockaddr_in6 *) addr)->sin6_addr;
addr->ip_length = sizeof(struct in6_addr);
addr->port = ntohs(((struct sockaddr_in6 *) addr)->sin6_port);
} else if (addr->mem.ss_family == AF_INET) {
addr->ip = (char *) &((struct sockaddr_in *) addr)->sin_addr;
addr->ip_length = sizeof(struct in_addr);
addr->port = ntohs(((struct sockaddr_in *) addr)->sin_port);
} else {
addr->ip_length = 0;
addr->port = -1;
}
}
int bsd_local_addr(LIBUS_SOCKET_DESCRIPTOR fd, struct bsd_addr_t *addr) {
addr->len = sizeof(addr->mem);
if (getsockname(fd, (struct sockaddr *) &addr->mem, &addr->len)) {
return -1;
}
internal_finalize_bsd_addr(addr);
return 0;
}
int bsd_remote_addr(LIBUS_SOCKET_DESCRIPTOR fd, struct bsd_addr_t *addr) {
addr->len = sizeof(addr->mem);
if (getpeername(fd, (struct sockaddr *) &addr->mem, &addr->len)) {
return -1;
}
internal_finalize_bsd_addr(addr);
return 0;
}
char *bsd_addr_get_ip(struct bsd_addr_t *addr) {
return addr->ip;
}
int bsd_addr_get_ip_length(struct bsd_addr_t *addr) {
return addr->ip_length;
}
int bsd_addr_get_port(struct bsd_addr_t *addr) {
return addr->port;
}
// called by dispatch_ready_poll
LIBUS_SOCKET_DESCRIPTOR bsd_accept_socket(LIBUS_SOCKET_DESCRIPTOR fd, struct bsd_addr_t *addr) {
LIBUS_SOCKET_DESCRIPTOR accepted_fd;
addr->len = sizeof(addr->mem);
#if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
// Linux, FreeBSD
accepted_fd = accept4(fd, (struct sockaddr *) addr, &addr->len, SOCK_CLOEXEC | SOCK_NONBLOCK);
#else
// Windows, OS X
accepted_fd = accept(fd, (struct sockaddr *) addr, &addr->len);
#endif
/* We cannot rely on addr since it is not initialized if failed */
if (accepted_fd == LIBUS_SOCKET_ERROR) {
return LIBUS_SOCKET_ERROR;
}
internal_finalize_bsd_addr(addr);
return bsd_set_nonblocking(apple_no_sigpipe(accepted_fd));
}
int bsd_recv(LIBUS_SOCKET_DESCRIPTOR fd, void *buf, int length, int flags) {
return recv(fd, buf, length, flags);
}
#if !defined(_WIN32)
#include <sys/uio.h>
int bsd_write2(LIBUS_SOCKET_DESCRIPTOR fd, const char *header, int header_length, const char *payload, int payload_length) {
struct iovec chunks[2];
chunks[0].iov_base = (char *)header;
chunks[0].iov_len = header_length;
chunks[1].iov_base = (char *)payload;
chunks[1].iov_len = payload_length;
return writev(fd, chunks, 2);
}
#else
int bsd_write2(LIBUS_SOCKET_DESCRIPTOR fd, const char *header, int header_length, const char *payload, int payload_length) {
int written = bsd_send(fd, header, header_length, 0);
if (written == header_length) {
int second_write = bsd_send(fd, payload, payload_length, 0);
if (second_write > 0) {
written += second_write;
}
}
return written;
}
#endif
int bsd_send(LIBUS_SOCKET_DESCRIPTOR fd, const char *buf, int length, int msg_more) {
// MSG_MORE (Linux), MSG_PARTIAL (Windows), TCP_NOPUSH (BSD)
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
#ifdef MSG_MORE
// for Linux we do not want signals
return send(fd, buf, length, ((msg_more != 0) * MSG_MORE) | MSG_NOSIGNAL);
#else
// use TCP_NOPUSH
return send(fd, buf, length, MSG_NOSIGNAL);
#endif
}
int bsd_would_block() {
#ifdef _WIN32
return WSAGetLastError() == WSAEWOULDBLOCK;
#else
return errno == EWOULDBLOCK;// || errno == EAGAIN;
#endif
}
// return LIBUS_SOCKET_ERROR or the fd that represents listen socket
// listen both on ipv6 and ipv4
LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket(const char *host, int port, int options) {
struct addrinfo hints, *result;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
char port_string[16];
snprintf(port_string, 16, "%d", port);
if (getaddrinfo(host, port_string, &hints, &result)) {
return LIBUS_SOCKET_ERROR;
}
LIBUS_SOCKET_DESCRIPTOR listenFd = LIBUS_SOCKET_ERROR;
struct addrinfo *listenAddr;
for (struct addrinfo *a = result; a && listenFd == LIBUS_SOCKET_ERROR; a = a->ai_next) {
if (a->ai_family == AF_INET6) {
listenFd = bsd_create_socket(a->ai_family, a->ai_socktype, a->ai_protocol);
listenAddr = a;
}
}
for (struct addrinfo *a = result; a && listenFd == LIBUS_SOCKET_ERROR; a = a->ai_next) {
if (a->ai_family == AF_INET) {
listenFd = bsd_create_socket(a->ai_family, a->ai_socktype, a->ai_protocol);
listenAddr = a;
}
}
if (listenFd == LIBUS_SOCKET_ERROR) {
freeaddrinfo(result);
return LIBUS_SOCKET_ERROR;
}
if (port != 0) {
/* Otherwise, always enable SO_REUSEPORT and SO_REUSEADDR _unless_ options specify otherwise */
#ifdef _WIN32
if (options & LIBUS_LISTEN_EXCLUSIVE_PORT) {
int optval2 = 1;
setsockopt(listenFd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &optval2, sizeof(optval2));
} else {
int optval3 = 1;
setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, (void *) &optval3, sizeof(optval3));
}
#else
#if /*defined(__linux) &&*/ defined(SO_REUSEPORT)
if (!(options & LIBUS_LISTEN_EXCLUSIVE_PORT)) {
int optval = 1;
setsockopt(listenFd, SOL_SOCKET, SO_REUSEPORT, (void *) &optval, sizeof(optval));
}
#endif
int enabled = 1;
setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, (void *) &enabled, sizeof(enabled));
#endif
}
#ifdef IPV6_V6ONLY
int disabled = 0;
setsockopt(listenFd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &disabled, sizeof(disabled));
#endif
if (bind(listenFd, listenAddr->ai_addr, (socklen_t) listenAddr->ai_addrlen) || listen(listenFd, 16384)) {
bsd_close_socket(listenFd);
freeaddrinfo(result);
return LIBUS_SOCKET_ERROR;
}
freeaddrinfo(result);
return listenFd;
}
#ifndef _WIN32
#include <sys/un.h>
#else
#include <afunix.h>
#include <io.h>
#endif
#include <sys/stat.h>
#include <stddef.h>
LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket_unix(const char *path, int options) {
LIBUS_SOCKET_DESCRIPTOR listenFd = LIBUS_SOCKET_ERROR;
listenFd = bsd_create_socket(AF_UNIX, SOCK_STREAM, 0);
if (listenFd == LIBUS_SOCKET_ERROR) {
return LIBUS_SOCKET_ERROR;
}
#ifndef _WIN32
// 700 permission by default
fchmod(listenFd, S_IRWXU);
#else
_chmod(path, S_IREAD | S_IWRITE | S_IEXEC);
#endif
struct sockaddr_un server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, path);
int size = offsetof(struct sockaddr_un, sun_path) + strlen(server_address.sun_path);
#ifdef _WIN32
_unlink(path);
#else
unlink(path);
#endif
if (bind(listenFd, (struct sockaddr *)&server_address, size) || listen(listenFd, 16384)) {
bsd_close_socket(listenFd);
return LIBUS_SOCKET_ERROR;
}
return listenFd;
}
LIBUS_SOCKET_DESCRIPTOR bsd_create_udp_socket(const char *host, int port) {
struct addrinfo hints, *result;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
char port_string[16];
snprintf(port_string, 16, "%d", port);
if (getaddrinfo(host, port_string, &hints, &result)) {
return LIBUS_SOCKET_ERROR;
}
LIBUS_SOCKET_DESCRIPTOR listenFd = LIBUS_SOCKET_ERROR;
struct addrinfo *listenAddr;
for (struct addrinfo *a = result; a && listenFd == LIBUS_SOCKET_ERROR; a = a->ai_next) {
if (a->ai_family == AF_INET6) {
listenFd = bsd_create_socket(a->ai_family, a->ai_socktype, a->ai_protocol);
listenAddr = a;
}
}
for (struct addrinfo *a = result; a && listenFd == LIBUS_SOCKET_ERROR; a = a->ai_next) {
if (a->ai_family == AF_INET) {
listenFd = bsd_create_socket(a->ai_family, a->ai_socktype, a->ai_protocol);
listenAddr = a;
}
}
if (listenFd == LIBUS_SOCKET_ERROR) {
freeaddrinfo(result);
return LIBUS_SOCKET_ERROR;
}
if (port != 0) {
/* Should this also go for UDP? */
int enabled = 1;
setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, (void *) &enabled, sizeof(enabled));
}
#ifdef IPV6_V6ONLY
int disabled = 0;
setsockopt(listenFd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &disabled, sizeof(disabled));
#endif
/* We need destination address for udp packets in both ipv6 and ipv4 */
/* On FreeBSD this option seems to be called like so */
#ifndef IPV6_RECVPKTINFO
#define IPV6_RECVPKTINFO IPV6_PKTINFO
#endif
int enabled = 1;
if (setsockopt(listenFd, IPPROTO_IPV6, IPV6_RECVPKTINFO, (void *) &enabled, sizeof(enabled)) == -1) {
if (errno == 92) {
// Linux ipv4
#ifdef IP_PKTINFO
if (setsockopt(listenFd, IPPROTO_IP, IP_PKTINFO, (void *) &enabled, sizeof(enabled)) != 0) {
printf("Error setting IPv4 pktinfo!\n");
}
// FreeBSD ipv4
#elif IP_RECVDSTADDR
if (setsockopt(listenFd, IPPROTO_IP, IP_RECVDSTADDR, (void *) &enabled, sizeof(enabled)) != 0) {
printf("Error setting IPv4 pktinfo!\n");
}
#endif
} else {
printf("Error setting IPv6 pktinfo!\n");
}
}
/* These are used for getting the ECN */
if (setsockopt(listenFd, IPPROTO_IPV6, IPV6_RECVTCLASS, (void *) &enabled, sizeof(enabled)) == -1) {
if (errno == 92) {
if (setsockopt(listenFd, IPPROTO_IP, IP_RECVTOS, (void *) &enabled, sizeof(enabled)) != 0) {
printf("Error setting IPv4 ECN!\n");
}
} else {
printf("Error setting IPv6 ECN!\n");
}
}
/* We bind here as well */
if (bind(listenFd, listenAddr->ai_addr, (socklen_t) listenAddr->ai_addrlen)) {
bsd_close_socket(listenFd);
freeaddrinfo(result);
return LIBUS_SOCKET_ERROR;
}
freeaddrinfo(result);
return listenFd;
}
int bsd_udp_packet_buffer_ecn(void *msgvec, int index) {
#if defined(_WIN32) || defined(__APPLE__)
printf("ECN not supported!\n");
#else
// we should iterate all control messages once, after recvmmsg and then only fetch them with these functions
struct msghdr *mh = &((struct mmsghdr *) msgvec)[index].msg_hdr;
for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(mh); cmsg != NULL; cmsg = CMSG_NXTHDR(mh, cmsg)) {
// do we need to get TOS from ipv6 also?
if (cmsg->cmsg_level == IPPROTO_IP) {
if (cmsg->cmsg_type == IP_TOS) {
uint8_t tos = *(uint8_t *)CMSG_DATA(cmsg);
return tos & 3;
}
}
if (cmsg->cmsg_level == IPPROTO_IPV6) {
if (cmsg->cmsg_type == IPV6_TCLASS) {
// is this correct?
uint8_t tos = *(uint8_t *)CMSG_DATA(cmsg);
return tos & 3;
}
}
}
#endif
printf("We got no ECN!\n");
return 0; // no ecn defaults to 0
}
LIBUS_SOCKET_DESCRIPTOR bsd_create_connect_socket(const char *host, int port, const char *source_host, int options) {
struct addrinfo hints, *result;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
char port_string[16];
snprintf(port_string, 16, "%d", port);
if (getaddrinfo(host, port_string, &hints, &result) != 0) {
return LIBUS_SOCKET_ERROR;
}
LIBUS_SOCKET_DESCRIPTOR fd = bsd_create_socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (fd == LIBUS_SOCKET_ERROR) {
freeaddrinfo(result);
return LIBUS_SOCKET_ERROR;
}
if (source_host) {
struct addrinfo *interface_result;
if (!getaddrinfo(source_host, NULL, NULL, &interface_result)) {
int ret = bind(fd, interface_result->ai_addr, (socklen_t) interface_result->ai_addrlen);
freeaddrinfo(interface_result);
if (ret == LIBUS_SOCKET_ERROR) {
bsd_close_socket(fd);
freeaddrinfo(result);
return LIBUS_SOCKET_ERROR;
}
}
}
connect(fd, result->ai_addr, (socklen_t) result->ai_addrlen);
freeaddrinfo(result);
return fd;
}
LIBUS_SOCKET_DESCRIPTOR bsd_create_connect_socket_unix(const char *server_path, int options) {
struct sockaddr_un server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, server_path);
int size = offsetof(struct sockaddr_un, sun_path) + strlen(server_address.sun_path);
LIBUS_SOCKET_DESCRIPTOR fd = bsd_create_socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == LIBUS_SOCKET_ERROR) {
return LIBUS_SOCKET_ERROR;
}
connect(fd, (struct sockaddr *)&server_address, size);
return fd;
}
+51 -17
View File
@@ -1,11 +1,43 @@
module usockets
#flag -DLIBUS_USE_LIBUV
#flag -DLIBUS_NO_SSL
#flag -IC:/Users/admin/.vmodules/hono/usockets/include
#flag -LC:/Users/admin/.vmodules/hono/usockets/lib
#flag C:/Users/admin/.vmodules/hono/usockets/lib/libusockets_full.a
#flag -lws2_32 -liphlpapi -lpsapi -luserenv -lole32
// 条件编译:根据操作系统选择正确的路径和库
// @VMODROOT 指向包含 v.mod 的模块根目录 (v-hono/)
$if windows {
#flag -DLIBUS_USE_LIBUV
#flag -DLIBUS_NO_SSL
#flag -I@VMODROOT/usockets/include
#flag -L@VMODROOT/lib
#flag @VMODROOT/lib/libusockets_full.a
#flag -lws2_32 -liphlpapi -lpsapi -luserenv -lole32
} $else $if macos {
// macOS: 支持 Apple Silicon (M1/M2/M3) 和 Intel Mac
#flag -DLIBUS_USE_LIBUV
#flag -DLIBUS_NO_SSL
// libuv 路径 - 根据架构选择 Homebrew 路径
$if arm64 {
#flag -I/opt/homebrew/include
#flag -L/opt/homebrew/lib
} $else {
#flag -I/usr/local/include
#flag -L/usr/local/lib
}
// uSockets 库路径
#flag -I@VMODROOT/usockets/include
#flag -L@VMODROOT/lib
#flag @VMODROOT/lib/libusockets_full.a
#flag -luv
} $else {
// Linux 和其他平台
#flag -DLIBUS_USE_LIBUV
#flag -DLIBUS_NO_SSL
#flag -I@VMODROOT/usockets/include
#flag -L@VMODROOT/lib
#flag @VMODROOT/lib/libusockets_full.a
#flag -luv
}
#include "libusockets.h"
@@ -20,13 +52,13 @@ struct C.us_socket_t {}
struct C.us_listen_socket_t {}
struct C.us_socket_context_options_t {
key_file_name voidptr
cert_file_name voidptr
passphrase voidptr
dh_params_file_name voidptr
ca_file_name voidptr
ssl_ciphers voidptr
ssl_prefer_low_memory_usage int
key_file_name voidptr
cert_file_name voidptr
passphrase voidptr
dh_params_file_name voidptr
ca_file_name voidptr
ssl_ciphers voidptr
ssl_prefer_low_memory_usage int
}
fn C.us_create_loop(hint voidptr, wakeup_cb voidptr, pre_cb voidptr, post_cb voidptr, ext_size u32) Loop
@@ -54,15 +86,15 @@ fn empty_pre(loop Loop) {}
fn empty_post(loop Loop) {}
pub fn create_loop() Loop {
return C.us_create_loop(unsafe { nil }, empty_wakeup, empty_pre, empty_post, 0)
return C.us_create_loop(unsafe { nil }, empty_wakeup, empty_pre, empty_post, 0)
}
pub fn (l Loop) run() { C.us_loop_run(l) }
pub fn (l Loop) free() { C.us_loop_free(l) }
pub fn create_socket_context(loop Loop) SocketContext {
options := C.us_socket_context_options_t{}
return C.us_create_socket_context(0, loop, 0, options)
options := C.us_socket_context_options_t{}
return C.us_create_socket_context(0, loop, 0, options)
}
pub fn (ctx SocketContext) free() { C.us_socket_context_free(0, ctx) }
@@ -73,7 +105,9 @@ pub fn (ctx SocketContext) on_writable(h voidptr) { C.us_socket_context_on_writa
pub fn (ctx SocketContext) on_timeout(h voidptr) { C.us_socket_context_on_timeout(0, ctx, h) }
pub fn (ctx SocketContext) on_end(h voidptr) { C.us_socket_context_on_end(0, ctx, h) }
pub fn (ctx SocketContext) listen(port int) ListenSocket {
return C.us_socket_context_listen(0, ctx, unsafe { nil }, port, 0, 0)
// 参数: ssl=0, context, host=nil, port, options=LIBUS_LISTEN_DEFAULT(0), socket_ext_size=0
// 注意: backlog 是在 uSockets 库内部硬编码的,不通过此函数传递
return C.us_socket_context_listen(0, ctx, unsafe { nil }, port, 0, 0)
}
pub fn (s Socket) write_bytes(data string) int { return C.us_socket_write(0, s, data.str, data.len, 0) }
+191 -51
View File
@@ -49,6 +49,9 @@ pub fn (mut app Hono) listen_usockets(port int) {
// 使用 uSockets 启动服务器(带配置)
pub fn (mut app Hono) listen_usockets_with_config(config UsocketsConfig) {
// 优化:预计算中间件前缀排序
app.precompute_middleware_prefixes()
// 存储到全局变量
g_usockets_app = unsafe { &app }
g_usockets_config = config
@@ -102,9 +105,16 @@ fn usockets_on_data(s usockets.Socket, data &char, length int) usockets.Socket {
if g_usockets_app.use_fast_router {
if route_match := g_usockets_app.fast_router.match_route(method, path) {
mut hono_ctx := create_usockets_context(method, path, route_match.params, query_map, body)
middlewares := get_middlewares_for_path_usockets(g_usockets_app, path)
response := exec_middlewares_usockets(0, middlewares, mut hono_ctx, route_match.handler)
send_usockets_response(s, hono_ctx, response)
// 优化1:零中间件快速路径
if !g_usockets_app.has_middlewares {
response := route_match.handler.handle(mut hono_ctx)
send_usockets_response(s, hono_ctx, response)
} else {
middlewares := get_middlewares_for_path_usockets_optimized(g_usockets_app, path)
response := exec_middlewares_usockets(0, middlewares, mut hono_ctx, route_match.handler)
send_usockets_response(s, hono_ctx, response)
}
response_sent = true
}
}
@@ -113,9 +123,16 @@ fn usockets_on_data(s usockets.Socket, data &char, length int) usockets.Socket {
if !response_sent {
if route_match := g_usockets_app.context_hybrid_router.match_route(method, path) {
mut hono_ctx := create_usockets_context(method, path, route_match.params, query_map, body)
middlewares := get_middlewares_for_path_usockets(g_usockets_app, path)
response := exec_middlewares_usockets(0, middlewares, mut hono_ctx, route_match.handler)
send_usockets_response(s, hono_ctx, response)
// 优化1:零中间件快速路径
if !g_usockets_app.has_middlewares {
response := route_match.handler.handle(mut hono_ctx)
send_usockets_response(s, hono_ctx, response)
} else {
middlewares := get_middlewares_for_path_usockets_optimized(g_usockets_app, path)
response := exec_middlewares_usockets(0, middlewares, mut hono_ctx, route_match.handler)
send_usockets_response(s, hono_ctx, response)
}
response_sent = true
}
}
@@ -152,57 +169,119 @@ fn usockets_on_end(s usockets.Socket) usockets.Socket {
return s.close()
}
// 解析 HTTP 请求
// 解析 HTTP 请求 - 零分配优化版
// 使用指针遍历避免创建临时数组
fn parse_http_request_usockets(raw string) (string, string, map[string]string, string) {
mut method := ''
mut path := ''
mut query_map := map[string]string{}
mut body := ''
line_end := raw.index('\r\n') or { return method, path, query_map, body }
request_line := raw[..line_end]
parts := request_line.split(' ')
if parts.len < 2 {
len := raw.len
if len == 0 {
return method, path, query_map, body
}
method = parts[0]
full_path := parts[1]
if query_idx := full_path.index('?') {
path = full_path[..query_idx]
query_str := full_path[query_idx + 1..]
for part in query_str.split('&') {
if eq_idx := part.index('=') {
query_map[part[..eq_idx]] = part[eq_idx + 1..]
}
// 1. 查找第一行结束位置(\r\n)
mut line_end := -1
for i in 0 .. len - 1 {
if raw[i] == `\r` && raw[i + 1] == `\n` {
line_end = i
break
}
}
if line_end == -1 {
return method, path, query_map, body
}
// 2. 解析 method(到第一个空格)
mut method_end := 0
for method_end < line_end && raw[method_end] != ` ` {
method_end++
}
if method_end == 0 || method_end >= line_end {
return method, path, query_map, body
}
method = raw[..method_end]
// 3. 解析 path 和 query(从空格后到下一个空格)
mut path_start := method_end + 1
// 跳过多余空格
for path_start < line_end && raw[path_start] == ` ` {
path_start++
}
mut path_end := path_start
mut query_start := -1
for path_end < line_end && raw[path_end] != ` ` {
if raw[path_end] == `?` && query_start == -1 {
query_start = path_end + 1
}
path_end++
}
if query_start > 0 {
path = raw[path_start..query_start - 1]
// 解析 query string(单次遍历)
query_map = parse_query_string_fast(raw, query_start, path_end)
} else {
path = full_path
path = raw[path_start..path_end]
}
if body_start := raw.index('\r\n\r\n') {
body = raw[body_start + 4..]
// 4. 查找 body(\r\n\r\n 之后)
for i in line_end .. len - 3 {
if raw[i] == `\r` && raw[i + 1] == `\n` && raw[i + 2] == `\r` && raw[i + 3] == `\n` {
if i + 4 < len {
body = raw[i + 4..]
}
break
}
}
return method, path, query_map, body
}
// 创建 uSockets 上下文
// 快速解析 query string(单次遍历,避免 split)
@[inline]
fn parse_query_string_fast(raw string, start int, end int) map[string]string {
mut query_map := map[string]string{}
mut key_start := start
mut key_end := -1
mut value_start := -1
for i := start; i <= end; i++ {
ch := if i < end { raw[i] } else { `&` } // 末尾视为分隔符
if ch == `=` && key_end == -1 {
key_end = i
value_start = i + 1
} else if ch == `&` {
// 完成一个键值对
if key_end > key_start && value_start > 0 {
key := raw[key_start..key_end]
value := if value_start < i { raw[value_start..i] } else { '' }
query_map[key] = value
} else if key_end == -1 && i > key_start {
// 只有 key 没有 value
key := raw[key_start..i]
query_map[key] = ''
}
// 重置状态
key_start = i + 1
key_end = -1
value_start = -1
}
}
return query_map
}
// 创建 uSockets 上下文 - 优化版
fn create_usockets_context(method string, path string, params map[string]string, query map[string]string, body string) Context {
return Context{
req: http.Request{
method: match method {
'GET' { http.Method.get }
'POST' { http.Method.post }
'PUT' { http.Method.put }
'DELETE' { http.Method.delete }
'PATCH' { http.Method.patch }
'HEAD' { http.Method.head }
'OPTIONS' { http.Method.options }
else { http.Method.get }
}
method: parse_http_method_usockets(method)
url: path
data: body
}
@@ -216,14 +295,49 @@ fn create_usockets_context(method string, path string, params map[string]string,
}
}
// 获取路径对应的所有中间件
fn get_middlewares_for_path_usockets(app &Hono, path string) []ContextMiddleware {
// 快速 HTTP 方法解析(基于首字符和长度)
@[inline]
fn parse_http_method_usockets(method string) http.Method {
len := method.len
if len == 0 {
return http.Method.get
}
// 基于首字符快速分支
match method[0] {
`G` {
if len == 3 { return http.Method.get }
}
`P` {
if len == 4 && method[1] == `O` { return http.Method.post }
if len == 3 && method[1] == `U` { return http.Method.put }
if len == 5 { return http.Method.patch }
}
`D` {
if len == 6 { return http.Method.delete }
}
`H` {
if len == 4 { return http.Method.head }
}
`O` {
if len == 7 { return http.Method.options }
}
else {}
}
return http.Method.get
}
// 获取路径对应的所有中间件(优化版:使用预排序的前缀列表)
fn get_middlewares_for_path_usockets_optimized(app &Hono, path string) []ContextMiddleware {
// 优化2:只有全局中间件时,直接返回引用(避免克隆)
if app.route_middlewares.len == 0 {
return app.context_middlewares
}
mut middlewares := app.context_middlewares.clone()
mut prefixes := app.route_middlewares.keys()
prefixes.sort(a.len < b.len)
for prefix in prefixes {
// 优化3:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
for prefix in app.sorted_middleware_prefixes {
if path.starts_with(prefix) || prefix == '/' {
if mws := app.route_middlewares[prefix] {
middlewares << mws
@@ -234,6 +348,11 @@ fn get_middlewares_for_path_usockets(app &Hono, path string) []ContextMiddleware
return middlewares
}
// 获取路径对应的所有中间件(保留旧版本兼容)
fn get_middlewares_for_path_usockets(app &Hono, path string) []ContextMiddleware {
return get_middlewares_for_path_usockets_optimized(app, path)
}
// 执行中间件链
fn exec_middlewares_usockets(idx int, middlewares []ContextMiddleware, mut ctx Context, handler IHandler) http.Response {
if idx < middlewares.len {
@@ -245,7 +364,7 @@ fn exec_middlewares_usockets(idx int, middlewares []ContextMiddleware, mut ctx C
return handler.handle(mut ctx)
}
// 发送 uSockets 响应
// 发送 uSockets 响应 - 优化版
fn send_usockets_response(s usockets.Socket, ctx Context, response http.Response) {
status_code := if ctx.status_code != 0 { ctx.status_code } else { response.status_code }
@@ -261,20 +380,22 @@ fn send_usockets_response(s usockets.Socket, ctx Context, response http.Response
// 头部
mut has_content_type := false
for key, value in ctx.headers {
if key.to_lower() == 'content-length' {
// 使用快速大小写不敏感比较
key_len := key.len
if key_len == 14 && eq_ignore_case_usockets(key, 'content-length') {
continue
}
resp.write_string(key)
resp.write_string(': ')
resp.write_string(value)
resp.write_string('\r\n')
if key.to_lower() == 'content-type' {
if key_len == 12 && eq_ignore_case_usockets(key, 'content-type') {
has_content_type = true
}
}
if content_type := response.header.get(.content_type) {
if !has_content_type {
if !has_content_type {
if content_type := response.header.get(.content_type) {
resp.write_string('Content-Type: ')
resp.write_string(content_type)
resp.write_string('\r\n')
@@ -301,6 +422,25 @@ fn send_usockets_response(s usockets.Socket, ctx Context, response http.Response
s.write_bytes(resp.str())
}
// 大小写不敏感字符串比较(避免分配)
@[inline]
fn eq_ignore_case_usockets(a string, b string) bool {
if a.len != b.len {
return false
}
for i in 0 .. a.len {
ca := a[i]
cb := b[i]
// 转换为小写比较
la := if ca >= `A` && ca <= `Z` { ca + 32 } else { ca }
lb := if cb >= `A` && cb <= `Z` { cb + 32 } else { cb }
if la != lb {
return false
}
}
return true
}
// 获取状态码文本
fn get_status_text_usockets(code int) string {
return match code {
+1 -1
View File
@@ -1,7 +1,7 @@
Module {
name: 'hono'
description: 'A high-performance V language web framework inspired by Hono.js, featuring hybrid routing, LRU cache, middleware support, and more.'
version: '0.3.6'
version: '0.4.0'
license: 'MIT'
dependencies: []
}