Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43aae4f10d | ||
|
|
05bb2d6c95 | ||
|
|
9aefe5714d | ||
|
|
1fc22044c3 | ||
|
|
b478269d8e | ||
|
|
69d1385ced | ||
|
|
1482b9c4d9 | ||
|
|
0937dd268c | ||
|
|
07382ab622 | ||
|
|
5375b7394f |
@@ -36,6 +36,80 @@ git clone https://github.com/meiseayoung/v-hono.git
|
|||||||
cd v-hono
|
cd v-hono
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Build & Run
|
||||||
|
|
||||||
|
### Standard Build (picoev backend)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
v your_app.v -o app.exe
|
||||||
|
./app.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
### High-Performance Build (uSockets backend)
|
||||||
|
|
||||||
|
For maximum performance with uSockets backend:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
v -enable-globals -cc gcc -ldflags "-ldbghelp" your_app.v -o app.exe
|
||||||
|
./app.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: The `-enable-globals` flag is required for uSockets backend. The `-ldflags "-ldbghelp"` fixes Windows linking issues.
|
||||||
|
|
||||||
|
#### Windows Prerequisites
|
||||||
|
|
||||||
|
To use uSockets backend on Windows, you need:
|
||||||
|
|
||||||
|
1. **GCC (MinGW-w64)** - C compiler
|
||||||
|
```powershell
|
||||||
|
# Install via Scoop
|
||||||
|
scoop install mingw
|
||||||
|
|
||||||
|
# Or via Chocolatey
|
||||||
|
choco install mingw
|
||||||
|
|
||||||
|
# Or download from: https://www.mingw-w64.org/downloads/
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **V Compiler** - Version 0.4.x or later
|
||||||
|
```powershell
|
||||||
|
# Install via Scoop
|
||||||
|
scoop install vlang
|
||||||
|
|
||||||
|
# Or download from: https://vlang.io/
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Verify Installation**
|
||||||
|
```powershell
|
||||||
|
gcc --version # Should show MinGW-w64 GCC
|
||||||
|
v version # Should show V 0.4.x
|
||||||
|
```
|
||||||
|
|
||||||
|
The uSockets library and libuv are pre-compiled and included in the `usockets/lib/` directory.
|
||||||
|
|
||||||
|
### Using uSockets Backend
|
||||||
|
|
||||||
|
```v
|
||||||
|
import hono
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
mut app := hono.Hono.new()
|
||||||
|
|
||||||
|
app.get('/', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('Hello, World!')
|
||||||
|
})
|
||||||
|
|
||||||
|
// Use uSockets backend (high concurrency optimized)
|
||||||
|
app.listen_usockets(3000)
|
||||||
|
|
||||||
|
// Or use default picoev backend
|
||||||
|
// app.listen(':3000')
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
See [benchmark/README.md](benchmark/README.md) for performance benchmarks and [usockets/README.md](usockets/README.md) for uSockets integration details.
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
```v
|
```v
|
||||||
@@ -209,3 +283,5 @@ See the `examples/` directory for more examples:
|
|||||||
## License
|
## License
|
||||||
|
|
||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ pub mut:
|
|||||||
use_fast_router bool = true // 新增:是否使用快速路由器
|
use_fast_router bool = true // 新增:是否使用快速路由器
|
||||||
context_middlewares []ContextMiddleware
|
context_middlewares []ContextMiddleware
|
||||||
route_middlewares map[string][]ContextMiddleware // 路由前缀对应的中间件
|
route_middlewares map[string][]ContextMiddleware // 路由前缀对应的中间件
|
||||||
|
// 优化:预排序的中间件前缀列表(启动时计算一次)
|
||||||
|
sorted_middleware_prefixes []string
|
||||||
|
// 优化:标记是否有中间件(用于零中间件快速路径)
|
||||||
|
has_middlewares bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Context 中间件类型
|
// Context 中间件类型
|
||||||
@@ -185,6 +189,14 @@ pub fn (mut app Hono) all(path string, handler fn (mut Context) http.Response) {
|
|||||||
// Context 中间件
|
// Context 中间件
|
||||||
pub fn (mut app Hono) use(mw ContextMiddleware) {
|
pub fn (mut app Hono) use(mw ContextMiddleware) {
|
||||||
app.context_middlewares << mw
|
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 处理器
|
// notFound() - 自定义 404 处理器
|
||||||
@@ -215,25 +227,31 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析 query
|
// 解析 query - 优化:直接使用 url.raw_query 避免额外解析
|
||||||
raw_query := url.query().to_map()
|
|
||||||
mut query_map := map[string]string{}
|
mut query_map := map[string]string{}
|
||||||
for key, values in raw_query {
|
if url.raw_query.len > 0 {
|
||||||
if values.len > 0 {
|
query_map = parse_query_string_app(url.raw_query)
|
||||||
query_map[key] = values[0]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 缓存 method 字符串,避免多次调用 .str()
|
||||||
|
method_str := req.method.str()
|
||||||
|
|
||||||
// 尝试 Context 路由
|
// 尝试 Context 路由
|
||||||
// 优先使用快速路由器
|
// 优先使用快速路由器
|
||||||
if s.app.use_fast_router {
|
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 由路由匹配结果提供
|
||||||
param_map := route_match.params.clone()
|
param_map := route_match.params.clone()
|
||||||
// body
|
// body
|
||||||
body := req.data
|
body := req.data
|
||||||
// 构造 Context
|
// 构造 Context
|
||||||
mut ctx := Context.new(req, param_map, query_map, body)
|
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)
|
middlewares := s.get_middlewares_for_path(url.path)
|
||||||
// 洋葱模型递归执行中间件
|
// 洋葱模型递归执行中间件
|
||||||
@@ -243,13 +261,19 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 如果快速路由器没有匹配,回退到混合路由器
|
// 如果快速路由器没有匹配,回退到混合路由器
|
||||||
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 由路由匹配结果提供
|
||||||
param_map := route_match.params.clone()
|
param_map := route_match.params.clone()
|
||||||
// body
|
// body
|
||||||
body := req.data
|
body := req.data
|
||||||
// 构造 Context
|
// 构造 Context
|
||||||
mut ctx := Context.new(req, param_map, query_map, body)
|
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)
|
middlewares := s.get_middlewares_for_path(url.path)
|
||||||
// 洋葱模型递归执行中间件
|
// 洋葱模型递归执行中间件
|
||||||
@@ -258,13 +282,19 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
} else {
|
} 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 由路由匹配结果提供
|
||||||
param_map := route_match.params.clone()
|
param_map := route_match.params.clone()
|
||||||
// body
|
// body
|
||||||
body := req.data
|
body := req.data
|
||||||
// 构造 Context
|
// 构造 Context
|
||||||
mut ctx := Context.new(req, param_map, query_map, body)
|
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)
|
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 {
|
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 middlewares := s.app.context_middlewares.clone()
|
||||||
|
|
||||||
// 按前缀长度排序,确保更具体的前缀后执行
|
// 优化:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
|
||||||
mut prefixes := s.app.route_middlewares.keys()
|
for prefix in s.app.sorted_middleware_prefixes {
|
||||||
prefixes.sort(a.len < b.len)
|
|
||||||
|
|
||||||
for prefix in prefixes {
|
|
||||||
if path.starts_with(prefix) || prefix == '/' {
|
if path.starts_with(prefix) || prefix == '/' {
|
||||||
if mws := s.app.route_middlewares[prefix] {
|
if mws := s.app.route_middlewares[prefix] {
|
||||||
middlewares << mws
|
middlewares << mws
|
||||||
@@ -342,6 +374,9 @@ pub fn (mut app Hono) listen(port string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 优化:预计算中间件前缀排序
|
||||||
|
app.precompute_middleware_prefixes()
|
||||||
|
|
||||||
// 使用优化配置的 picoev 高性能服务器(支持高并发)
|
// 使用优化配置的 picoev 高性能服务器(支持高并发)
|
||||||
app.listen_picoev_with_config(PicoevConfig{
|
app.listen_picoev_with_config(PicoevConfig{
|
||||||
port: port_num
|
port: port_num
|
||||||
@@ -372,6 +407,7 @@ pub fn (mut app Hono) route(prefix string, mut subapp Hono) {
|
|||||||
} else {
|
} else {
|
||||||
app.route_middlewares[prefix] = subapp.context_middlewares.clone()
|
app.route_middlewares[prefix] = subapp.context_middlewares.clone()
|
||||||
}
|
}
|
||||||
|
app.has_middlewares = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// 继承子应用的 notFound 和 onError 处理器(如果主应用没有设置)
|
// 继承子应用的 notFound 和 onError 处理器(如果主应用没有设置)
|
||||||
@@ -508,5 +544,48 @@ pub fn Hono.new() Hono {
|
|||||||
fast_router: FastRouter.new()
|
fast_router: FastRouter.new()
|
||||||
use_fast_router: true
|
use_fast_router: true
|
||||||
route_middlewares: map[string][]ContextMiddleware{}
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# V-Hono Benchmark
|
||||||
|
|
||||||
|
Performance benchmarks for V-Hono web framework.
|
||||||
|
|
||||||
|
## Framework Comparison (500 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 |
|
||||||
|
|
||||||
|
### Performance Summary
|
||||||
|
|
||||||
|
- **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. Start Test Server
|
||||||
|
|
||||||
|
**uSockets backend:**
|
||||||
|
```bash
|
||||||
|
v -enable-globals -cc gcc -ldflags "-ldbghelp" benchmark/usockets_server.v -o server.exe
|
||||||
|
./server.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
**Picoev backend:**
|
||||||
|
```bash
|
||||||
|
v -enable-globals examples/picoev_example.v -o server.exe
|
||||||
|
./server.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Run Integration Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run benchmark/usockets_verify.go
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Run Performance Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 200 connections, 100K requests
|
||||||
|
go run tests/main.go -url "http://127.0.0.1:9998" -c 200 -n 100000
|
||||||
|
|
||||||
|
# 500 connections, 100K requests
|
||||||
|
go run tests/main.go -url "http://127.0.0.1:9998" -c 500 -n 100000
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Quick Concurrent Test (PowerShell)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell -File benchmark/quick_test.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test Files
|
||||||
|
|
||||||
|
| File | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `usockets_server.v` | uSockets test server with full API |
|
||||||
|
| `usockets_verify.go` | Go integration test (17 test cases) |
|
||||||
|
| `quick_test.ps1` | PowerShell concurrent test script |
|
||||||
|
| `../tests/main.go` | Go performance benchmark tool |
|
||||||
|
|
||||||
|
## Test Coverage
|
||||||
|
|
||||||
|
The integration test (`usockets_verify.go`) covers:
|
||||||
|
|
||||||
|
- ✅ Basic GET routes (root, health, static)
|
||||||
|
- ✅ Dynamic routes (single/multi/nested params)
|
||||||
|
- ✅ Query parameters
|
||||||
|
- ✅ Response formats (JSON, HTML, custom status)
|
||||||
|
- ✅ HTTP methods (POST, PUT, DELETE)
|
||||||
|
- ✅ Error handling (404)
|
||||||
|
- ✅ Keep-Alive connections
|
||||||
|
- ✅ Throughput performance
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
// uSockets 测试服务器
|
||||||
|
// 用于集成测试验证 uSockets 后端功能
|
||||||
|
//
|
||||||
|
// 编译运行:
|
||||||
|
// v -enable-globals -cc gcc -ldflags "-ldbghelp" benchmark/usockets_test_server.v -o usockets_test.exe
|
||||||
|
// .\usockets_test.exe
|
||||||
|
|
||||||
|
module main
|
||||||
|
|
||||||
|
import hono
|
||||||
|
import net.http
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
mut app := hono.Hono.new()
|
||||||
|
|
||||||
|
// 全局中间件 - 添加自定义响应头
|
||||||
|
app.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
|
||||||
|
mut resp := next(mut c)
|
||||||
|
c.headers['X-Middleware'] = 'applied'
|
||||||
|
return resp
|
||||||
|
})
|
||||||
|
|
||||||
|
// ==================== 基本路由 ====================
|
||||||
|
|
||||||
|
app.get('/', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('Hello World')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/health', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('OK')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/api/health', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('OK')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ==================== CRUD 路由 ====================
|
||||||
|
|
||||||
|
app.get('/api/users', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.json('{"users": []}')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/api/users', fn (mut c hono.Context) http.Response {
|
||||||
|
c.status(201)
|
||||||
|
return c.json('{"created": true}')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/api/users/:id', fn (mut c hono.Context) http.Response {
|
||||||
|
id := c.params['id'] or { '' }
|
||||||
|
return c.json('{"id": "${id}"}')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.put('/api/users/:id', fn (mut c hono.Context) http.Response {
|
||||||
|
id := c.params['id'] or { '' }
|
||||||
|
return c.json('{"id": "${id}", "updated": true}')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.delete('/api/users/:id', fn (mut c hono.Context) http.Response {
|
||||||
|
id := c.params['id'] or { '' }
|
||||||
|
return c.json('{"id": "${id}", "deleted": true}')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.patch('/api/users/:id', fn (mut c hono.Context) http.Response {
|
||||||
|
id := c.params['id'] or { '' }
|
||||||
|
return c.json('{"id": "${id}", "patched": true}')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ==================== 多参数路由 ====================
|
||||||
|
|
||||||
|
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/categories/:category/items/:item', fn (mut c hono.Context) http.Response {
|
||||||
|
category := c.params['category'] or { '' }
|
||||||
|
item := c.params['item'] or { '' }
|
||||||
|
return c.json('{"category": "${category}", "item": "${item}"}')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ==================== 查询参数路由 ====================
|
||||||
|
|
||||||
|
app.get('/api/search', fn (mut c hono.Context) http.Response {
|
||||||
|
q := c.query['q'] or { '' }
|
||||||
|
limit := c.query['limit'] or { '10' }
|
||||||
|
page := c.query['page'] or { '1' }
|
||||||
|
return c.json('{"query": "${q}", "limit": ${limit}, "page": ${page}}')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ==================== 响应格式路由 ====================
|
||||||
|
|
||||||
|
app.get('/api/json', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.json('{"message": "JSON response"}')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/api/html', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.html('<html><body><h1>HTML Response</h1></body></html>')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/api/created', fn (mut c hono.Context) http.Response {
|
||||||
|
c.status(201)
|
||||||
|
return c.json('{"created": true}')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/api/custom-header', fn (mut c hono.Context) http.Response {
|
||||||
|
c.headers['X-Custom-Header'] = 'custom-value'
|
||||||
|
return c.text('OK')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ==================== 自定义 404 ====================
|
||||||
|
|
||||||
|
app.not_found(fn (mut c hono.Context) http.Response {
|
||||||
|
c.status(404)
|
||||||
|
return c.json('{"error": "Not Found", "path": "${c.path}"}')
|
||||||
|
})
|
||||||
|
|
||||||
|
// 启动 uSockets 服务器
|
||||||
|
println('[usockets-test-server] Starting on port 9998...')
|
||||||
|
app.listen_usockets(9998)
|
||||||
|
}
|
||||||
@@ -0,0 +1,468 @@
|
|||||||
|
// uSockets 功能验证测试
|
||||||
|
// go run benchmark/usockets_verify.go
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const baseURL = "http://127.0.0.1:9998"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println("╔═══════════════════════════════════════════════════════════════╗")
|
||||||
|
fmt.Println("║ uSockets 集成测试 ║")
|
||||||
|
fmt.Println("╚═══════════════════════════════════════════════════════════════╝")
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
client := &http.Client{Timeout: 5 * time.Second}
|
||||||
|
|
||||||
|
// 检查服务器
|
||||||
|
fmt.Print("🔍 检查测试服务器... ")
|
||||||
|
if !checkServer(client) {
|
||||||
|
fmt.Println("❌ 服务器未运行")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Println("✅")
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
total, passed, failed := 0, 0, 0
|
||||||
|
var errors []string
|
||||||
|
|
||||||
|
// 1. 基本 GET 路由测试
|
||||||
|
fmt.Println("📦 1. 基本 GET 路由测试")
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 GET 根路径... ")
|
||||||
|
if checkGetRoot(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "GET 根路径")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 GET 健康检查... ")
|
||||||
|
if checkGetHealth(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "GET 健康检查")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 GET 静态路由... ")
|
||||||
|
if checkGetStatic(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "GET 静态路由")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// 2. 动态路由测试
|
||||||
|
fmt.Println("📦 2. 动态路由测试")
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 单参数路由... ")
|
||||||
|
if checkSingleParam(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "单参数路由")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 多参数路由... ")
|
||||||
|
if checkMultiParams(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "多参数路由")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 嵌套参数路由... ")
|
||||||
|
if checkNestedParams(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "嵌套参数路由")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// 3. 查询参数测试
|
||||||
|
fmt.Println("📦 3. 查询参数测试")
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 单个查询参数... ")
|
||||||
|
if checkSingleQuery(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "单个查询参数")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 多个查询参数... ")
|
||||||
|
if checkMultiQuery(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "多个查询参数")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// 4. 响应格式测试
|
||||||
|
fmt.Println("📦 4. 响应格式测试")
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 JSON 响应... ")
|
||||||
|
if checkJSONResponse(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "JSON 响应")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 HTML 响应... ")
|
||||||
|
if checkHTMLResponse(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "HTML 响应")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 自定义状态码 201... ")
|
||||||
|
if checkCustomStatus(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "自定义状态码 201")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// 5. HTTP 方法测试
|
||||||
|
fmt.Println("📦 5. HTTP 方法测试")
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 POST 请求... ")
|
||||||
|
if checkPOST(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "POST 请求")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 PUT 请求... ")
|
||||||
|
if checkPUT(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "PUT 请求")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 DELETE 请求... ")
|
||||||
|
if checkDELETE(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "DELETE 请求")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// 6. 错误处理测试
|
||||||
|
fmt.Println("📦 6. 错误处理测试")
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 404 未找到... ")
|
||||||
|
if checkNotFound(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "404 未找到")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// 7. Keep-Alive 测试
|
||||||
|
fmt.Println("📦 7. Keep-Alive 连接测试")
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 连接复用... ")
|
||||||
|
if checkKeepAlive(client) {
|
||||||
|
passed++
|
||||||
|
fmt.Println("✅")
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "连接复用")
|
||||||
|
fmt.Println("❌")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// 8. 性能测试
|
||||||
|
fmt.Println("📦 8. 性能测试")
|
||||||
|
|
||||||
|
total++
|
||||||
|
fmt.Print(" 🧪 吞吐量测试... ")
|
||||||
|
rps := checkThroughput(client)
|
||||||
|
if rps > 100 {
|
||||||
|
passed++
|
||||||
|
fmt.Printf("✅ (%.0f req/s)\n", rps)
|
||||||
|
} else {
|
||||||
|
failed++
|
||||||
|
errors = append(errors, "吞吐量")
|
||||||
|
fmt.Printf("❌ (%.0f req/s)\n", rps)
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
// 输出总结
|
||||||
|
fmt.Println("═══════════════════════════════════════════════════════════════")
|
||||||
|
fmt.Printf("📊 测试结果: %d/%d 通过\n", passed, total)
|
||||||
|
|
||||||
|
if failed > 0 {
|
||||||
|
fmt.Println("❌ 失败的测试:")
|
||||||
|
for _, err := range errors {
|
||||||
|
fmt.Printf(" - %s\n", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Println("🎉 所有测试通过!uSockets 后端验证成功!")
|
||||||
|
}
|
||||||
|
fmt.Println("═══════════════════════════════════════════════════════════════")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkServer(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/health")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
return resp.StatusCode == 200
|
||||||
|
}
|
||||||
|
|
||||||
|
func getBody(resp *http.Response) string {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return string(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkGetRoot(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(body, "Hello")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkGetHealth(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/health")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && body == "OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkGetStatic(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/health")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && body == "OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkSingleParam(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/users/456")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(body, "456")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkMultiParams(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/users/123/posts/789")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(body, "123") && strings.Contains(body, "789")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkNestedParams(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/categories/tech/items/laptop")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(body, "tech") && strings.Contains(body, "laptop")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkSingleQuery(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/search?q=test")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(body, "test")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkMultiQuery(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/search?q=hello&limit=10&page=1")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(body, "hello")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkJSONResponse(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/json")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
ct := resp.Header.Get("Content-Type")
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(ct, "application/json")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkHTMLResponse(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/html")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
ct := resp.Header.Get("Content-Type")
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(ct, "text/html")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkCustomStatus(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/api/created")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
return resp.StatusCode == 201
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkPOST(client *http.Client) bool {
|
||||||
|
resp, err := client.Post(baseURL+"/api/users", "application/json", nil)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 201 && strings.Contains(body, "created")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkPUT(client *http.Client) bool {
|
||||||
|
req, _ := http.NewRequest("PUT", baseURL+"/api/users/123", nil)
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(body, "updated")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkDELETE(client *http.Client) bool {
|
||||||
|
req, _ := http.NewRequest("DELETE", baseURL+"/api/users/123", nil)
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body := getBody(resp)
|
||||||
|
return resp.StatusCode == 200 && strings.Contains(body, "deleted")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkNotFound(client *http.Client) bool {
|
||||||
|
resp, err := client.Get(baseURL + "/nonexistent/path")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
return resp.StatusCode == 404
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkKeepAlive(client *http.Client) bool {
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
resp, err := client.Get(baseURL + "/health")
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkThroughput(client *http.Client) float64 {
|
||||||
|
start := time.Now()
|
||||||
|
success := 0
|
||||||
|
requests := 200
|
||||||
|
|
||||||
|
for i := 0; i < requests; i++ {
|
||||||
|
resp, err := client.Get(baseURL + "/health")
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
io.Copy(io.Discard, resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode == 200 {
|
||||||
|
success++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
elapsed := time.Since(start).Seconds()
|
||||||
|
return float64(success) / elapsed
|
||||||
|
}
|
||||||
@@ -336,3 +336,71 @@ pub fn (mut cache ContextLRUCache) clear() {
|
|||||||
cache.size = 0
|
cache.size = 0
|
||||||
cache.last_cleanup = time.now().unix()
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
module main
|
||||||
|
|
||||||
|
import net.http
|
||||||
|
import hono
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
mut app := hono.Hono.new()
|
||||||
|
|
||||||
|
app.get('/', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('Hello from V-Hono + picoev!')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/json', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.json('{"message": "Hello, JSON!"}')
|
||||||
|
})
|
||||||
|
|
||||||
|
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}"}')
|
||||||
|
})
|
||||||
|
|
||||||
|
// 使用默认 picoev 后端
|
||||||
|
app.listen(':3009')
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
module main
|
||||||
|
|
||||||
|
import net.http
|
||||||
|
import hono
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
mut app := hono.Hono.new()
|
||||||
|
|
||||||
|
app.get('/', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('Hello from V-Hono + uSockets!')
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/json', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.json('{"message": "Hello, JSON!"}')
|
||||||
|
})
|
||||||
|
|
||||||
|
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}"}')
|
||||||
|
})
|
||||||
|
|
||||||
|
// 使用 uSockets 后端
|
||||||
|
app.listen_usockets(3008)
|
||||||
|
}
|
||||||
+25
-10
@@ -27,10 +27,12 @@ pub mut:
|
|||||||
static_routes map[string]IHandler
|
static_routes map[string]IHandler
|
||||||
static_route_results map[string]ContextRouteMatch // 预分配的静态路由结果
|
static_route_results map[string]ContextRouteMatch // 预分配的静态路由结果
|
||||||
precompiled_routes []PrecompiledRoute
|
precompiled_routes []PrecompiledRoute
|
||||||
lru_cache ContextLRUCache // 使用 LRU 缓存替代简单 map
|
fast_cache FastRouteCache // 使用高性能缓存替代 LRU
|
||||||
|
lru_cache ContextLRUCache // 保留 LRU 缓存用于兼容
|
||||||
regex_cache map[string]FastCompiledRegex // 正则表达式缓存
|
regex_cache map[string]FastCompiledRegex // 正则表达式缓存
|
||||||
cache_enabled bool = true
|
cache_enabled bool = true
|
||||||
sort_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_routes: map[string]IHandler{}
|
||||||
static_route_results: map[string]ContextRouteMatch{}
|
static_route_results: map[string]ContextRouteMatch{}
|
||||||
precompiled_routes: []PrecompiledRoute{}
|
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{}
|
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_routes: map[string]IHandler{}
|
||||||
static_route_results: map[string]ContextRouteMatch{}
|
static_route_results: map[string]ContextRouteMatch{}
|
||||||
precompiled_routes: []PrecompiledRoute{}
|
precompiled_routes: []PrecompiledRoute{}
|
||||||
|
fast_cache: FastRouteCache.new(cache_size * 10) // 高性能缓存
|
||||||
lru_cache: ContextLRUCache.new(cache_size)
|
lru_cache: ContextLRUCache.new(cache_size)
|
||||||
regex_cache: map[string]FastCompiledRegex{}
|
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 {
|
pub fn (mut router FastRouter) match_route(method string, path string) ?ContextRouteMatch {
|
||||||
|
// 优化:只拼接一次 cache key,复用于静态路由和缓存查找
|
||||||
|
cache_key := '${method}:${path}'
|
||||||
|
|
||||||
// 1. 静态路由直接返回预分配的结果(零分配)
|
// 1. 静态路由直接返回预分配的结果(零分配)
|
||||||
static_key := '${method}:${path}'
|
if result := router.static_route_results[cache_key] {
|
||||||
if result := router.static_route_results[static_key] {
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 动态路由先检查 LRU 缓存(避免重复正则匹配)
|
// 2. 动态路由先检查高性能缓存(零开销查找)
|
||||||
if router.cache_enabled {
|
if router.cache_enabled && router.use_fast_cache {
|
||||||
cache_key := '${method}:${path}'
|
if cached := router.fast_cache.get(cache_key) {
|
||||||
|
return cached
|
||||||
|
}
|
||||||
|
} else if router.cache_enabled {
|
||||||
|
// 回退到 LRU 缓存
|
||||||
if cached := router.lru_cache.get(cache_key) {
|
if cached := router.lru_cache.get(cache_key) {
|
||||||
return cached
|
return cached
|
||||||
}
|
}
|
||||||
@@ -208,11 +220,14 @@ pub fn (mut router FastRouter) match_route(method string, path string) ?ContextR
|
|||||||
base_path: ''
|
base_path: ''
|
||||||
}
|
}
|
||||||
|
|
||||||
// 只缓存动态路由结果
|
// 缓存动态路由结果
|
||||||
if router.cache_enabled {
|
if router.cache_enabled {
|
||||||
cache_key := '${method}:${path}'
|
if router.use_fast_cache {
|
||||||
|
router.fast_cache.put(cache_key, result)
|
||||||
|
} else {
|
||||||
router.lru_cache.put(cache_key, result)
|
router.lru_cache.put(cache_key, result)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|||||||
+199
-45
@@ -79,7 +79,15 @@ fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picoht
|
|||||||
if ctx.app.use_fast_router {
|
if ctx.app.use_fast_router {
|
||||||
if route_match := ctx.app.fast_router.match_route(method_str, path) {
|
if route_match := ctx.app.fast_router.match_route(method_str, path) {
|
||||||
mut hono_ctx := create_picoev_context(req, route_match.params, query_map)
|
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)
|
response := exec_middlewares_picoev(0, middlewares, mut hono_ctx, route_match.handler)
|
||||||
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
||||||
return
|
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) {
|
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)
|
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)
|
response := exec_middlewares_picoev(0, middlewares, mut hono_ctx, route_match.handler)
|
||||||
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
||||||
return
|
return
|
||||||
@@ -118,25 +134,76 @@ fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picoht
|
|||||||
res.end()
|
res.end()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查客户端是否请求 Keep-Alive
|
// 检查客户端是否请求 Keep-Alive - 优化版
|
||||||
|
// 避免 to_lower() 创建新字符串,使用大小写不敏感比较
|
||||||
fn check_keepalive_request(req picohttpparser.Request) bool {
|
fn check_keepalive_request(req picohttpparser.Request) bool {
|
||||||
for i in 0 .. req.num_headers {
|
for i in 0 .. req.num_headers {
|
||||||
h := req.headers[i]
|
h := req.headers[i]
|
||||||
if h.name.to_lower() == 'connection' {
|
// 大小写不敏感比较 "connection"
|
||||||
return h.value.to_lower().contains('keep-alive')
|
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
|
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 middlewares := app.context_middlewares.clone()
|
||||||
|
|
||||||
mut prefixes := app.route_middlewares.keys()
|
// 优化:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
|
||||||
prefixes.sort(a.len < b.len)
|
for prefix in app.sorted_middleware_prefixes {
|
||||||
|
|
||||||
for prefix in prefixes {
|
|
||||||
if path.starts_with(prefix) || prefix == '/' {
|
if path.starts_with(prefix) || prefix == '/' {
|
||||||
if mws := app.route_middlewares[prefix] {
|
if mws := app.route_middlewares[prefix] {
|
||||||
middlewares << mws
|
middlewares << mws
|
||||||
@@ -147,6 +214,11 @@ fn get_middlewares_for_path_picoev(app &Hono, path string) []ContextMiddleware {
|
|||||||
return middlewares
|
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 {
|
fn exec_middlewares_picoev(idx int, middlewares []ContextMiddleware, mut ctx Context, handler IHandler) http.Response {
|
||||||
if idx < middlewares.len {
|
if idx < middlewares.len {
|
||||||
@@ -158,40 +230,96 @@ fn exec_middlewares_picoev(idx int, middlewares []ContextMiddleware, mut ctx Con
|
|||||||
return handler.handle(mut ctx)
|
return handler.handle(mut ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析路径和查询参数
|
// 解析路径和查询参数 - 零分配优化版
|
||||||
|
// 使用指针遍历避免创建临时数组
|
||||||
fn parse_path_and_query(full_path string) (string, map[string]string) {
|
fn parse_path_and_query(full_path string) (string, map[string]string) {
|
||||||
mut query_map := map[string]string{}
|
mut query_map := map[string]string{}
|
||||||
|
len := full_path.len
|
||||||
|
|
||||||
if idx := full_path.index('?') {
|
if len == 0 {
|
||||||
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
|
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 {
|
fn create_picoev_context(req picohttpparser.Request, params map[string]string, query map[string]string) Context {
|
||||||
|
// 提取纯路径(不含查询参数)
|
||||||
|
path := extract_path_only(req.path)
|
||||||
|
|
||||||
return Context{
|
return Context{
|
||||||
req: convert_picoev_request(req)
|
req: convert_picoev_request(req)
|
||||||
params: params
|
params: params
|
||||||
query: query
|
query: query
|
||||||
body: req.body
|
body: req.body
|
||||||
url: req.path
|
url: req.path
|
||||||
path: req.path
|
path: path
|
||||||
status_code: 200
|
status_code: 200
|
||||||
headers: map[string]string{}
|
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 {
|
fn convert_picoev_request(req picohttpparser.Request) http.Request {
|
||||||
mut headers := http.new_header()
|
mut headers := http.new_header()
|
||||||
|
|
||||||
@@ -201,23 +329,46 @@ fn convert_picoev_request(req picohttpparser.Request) http.Request {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return http.Request{
|
return http.Request{
|
||||||
method: match req.method {
|
method: parse_http_method_fast(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 }
|
|
||||||
}
|
|
||||||
url: req.path
|
url: req.path
|
||||||
data: req.body
|
data: req.body
|
||||||
header: headers
|
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) {
|
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 }
|
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
|
mut has_connection := false
|
||||||
|
|
||||||
for key, value in ctx.headers {
|
for key, value in ctx.headers {
|
||||||
// 跳过 Content-Length,picohttpparser 会在 body() 时自动添加
|
// 使用快速大小写不敏感比较
|
||||||
if key.to_lower() == 'content-length' {
|
key_len := key.len
|
||||||
continue
|
if key_len == 14 && eq_ignore_case(key, 'content-length') {
|
||||||
|
continue // 跳过 Content-Length
|
||||||
}
|
}
|
||||||
res.header(key, value)
|
res.header(key, value)
|
||||||
key_lower := key.to_lower()
|
if key_len == 12 && eq_ignore_case(key, 'content-type') {
|
||||||
if key_lower == 'content-type' { has_content_type = true }
|
has_content_type = true
|
||||||
if key_lower == 'connection' { has_connection = 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)
|
res.header('Content-Type', content_type)
|
||||||
has_content_type = true
|
has_content_type = true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -208,10 +208,34 @@ pub fn (router ContextHybridRouter) match_static_route(method string, path strin
|
|||||||
return none
|
return none
|
||||||
}
|
}
|
||||||
|
|
||||||
// Context 版本的动态路径匹配
|
// Context 版本的动态路径匹配(保留旧版本兼容)
|
||||||
fn (mut router ContextHybridRouter) match_dynamic_route(method string, path string) ?ContextRouteMatch {
|
fn (mut router ContextHybridRouter) match_dynamic_route(method string, path string) ?ContextRouteMatch {
|
||||||
// 先检查缓存
|
|
||||||
cache_key := '${method}:${path}'
|
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) {
|
if cached := router.cache.get(cache_key) {
|
||||||
return cached
|
return cached
|
||||||
}
|
}
|
||||||
@@ -240,22 +264,6 @@ fn (mut router ContextHybridRouter) match_dynamic_route(method string, path stri
|
|||||||
return none
|
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 版本的获取所有路由
|
// Context 版本的获取所有路由
|
||||||
pub fn (router ContextHybridRouter) get_all_routes() ([]string, []string) {
|
pub fn (router ContextHybridRouter) get_all_routes() ([]string, []string) {
|
||||||
mut static_paths := []string{}
|
mut static_paths := []string{}
|
||||||
|
|||||||
@@ -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✅ 测试完成!")
|
||||||
|
}
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
url := flag.String("url", "http://127.0.0.1:3000", "Target base URL")
|
||||||
|
connections := flag.Int("c", 500, "Number of connections")
|
||||||
|
requests := flag.Int("n", 1000000, "Total number of requests")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
fmt.Printf("Benchmarking %s/users/:id\n", *url)
|
||||||
|
fmt.Printf("Connections: %d, Requests: %d\n\n", *connections, *requests)
|
||||||
|
|
||||||
|
client := &http.Client{
|
||||||
|
Transport: &http.Transport{
|
||||||
|
MaxIdleConns: *connections,
|
||||||
|
MaxIdleConnsPerHost: *connections,
|
||||||
|
MaxConnsPerHost: *connections,
|
||||||
|
IdleConnTimeout: 90 * time.Second,
|
||||||
|
},
|
||||||
|
Timeout: 10 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
var completed int64
|
||||||
|
var errors int64
|
||||||
|
var latencies []int64
|
||||||
|
var mu sync.Mutex
|
||||||
|
totalReqs := int64(*requests)
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for i := 0; i < *connections; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for {
|
||||||
|
if atomic.LoadInt64(&completed)+atomic.LoadInt64(&errors) >= totalReqs {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reqStart := time.Now()
|
||||||
|
userId := rand.Intn(10000)
|
||||||
|
targetUrl := fmt.Sprintf("%s/users/%d", *url, userId)
|
||||||
|
resp, err := client.Get(targetUrl)
|
||||||
|
if err != nil {
|
||||||
|
atomic.AddInt64(&errors, 1)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
io.Copy(io.Discard, resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
latency := time.Since(reqStart).Microseconds()
|
||||||
|
mu.Lock()
|
||||||
|
latencies = append(latencies, latency)
|
||||||
|
mu.Unlock()
|
||||||
|
atomic.AddInt64(&completed, 1)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
elapsed := time.Since(start).Seconds()
|
||||||
|
total := atomic.LoadInt64(&completed)
|
||||||
|
errs := atomic.LoadInt64(&errors)
|
||||||
|
rps := float64(total) / elapsed
|
||||||
|
|
||||||
|
mu.Lock()
|
||||||
|
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
|
||||||
|
var avg, p50, p95, p99 int64
|
||||||
|
if len(latencies) > 0 {
|
||||||
|
var sum int64
|
||||||
|
for _, l := range latencies {
|
||||||
|
sum += l
|
||||||
|
}
|
||||||
|
avg = sum / int64(len(latencies))
|
||||||
|
p50 = latencies[len(latencies)*50/100]
|
||||||
|
p95 = latencies[len(latencies)*95/100]
|
||||||
|
p99 = latencies[len(latencies)*99/100]
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
|
|
||||||
|
fmt.Println("Results:")
|
||||||
|
fmt.Printf(" Requests: %d\n", total)
|
||||||
|
fmt.Printf(" Errors: %d\n", errs)
|
||||||
|
fmt.Printf(" Duration: %.2fs\n", elapsed)
|
||||||
|
fmt.Printf(" RPS: %.0f\n", rps)
|
||||||
|
fmt.Printf(" Latency avg: %.2fms\n", float64(avg)/1000)
|
||||||
|
fmt.Printf(" Latency p50: %.2fms\n", float64(p50)/1000)
|
||||||
|
fmt.Printf(" Latency p95: %.2fms\n", float64(p95)/1000)
|
||||||
|
fmt.Printf(" Latency p99: %.2fms\n", float64(p99)/1000)
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// 测试缓存命中率
|
||||||
|
module main
|
||||||
|
|
||||||
|
import 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=== 测试完成 ===')
|
||||||
|
}
|
||||||
@@ -0,0 +1,381 @@
|
|||||||
|
// FastCache 优化测试
|
||||||
|
// 验证高性能缓存的正确性和性能
|
||||||
|
module main
|
||||||
|
|
||||||
|
import 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}'}
|
||||||
|
}
|
||||||
@@ -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('测试完成!')
|
||||||
|
}
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
// 中间件优化测试
|
||||||
|
// 测试三个优化点:
|
||||||
|
// 1. 零中间件快速路径
|
||||||
|
// 2. 中间件预计算(启动时排序)
|
||||||
|
// 3. 复用 cache key
|
||||||
|
|
||||||
|
import 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()
|
||||||
|
}
|
||||||
Executable
BIN
Binary file not shown.
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
Executable
BIN
Binary file not shown.
@@ -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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// uSockets 测试服务器
|
||||||
|
module main
|
||||||
|
|
||||||
|
import net.http
|
||||||
|
import 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// uSockets 简化测试服务器 - 与外层 main.v 配置一致
|
||||||
|
module main
|
||||||
|
|
||||||
|
import 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# uSockets Backend for V-Hono
|
||||||
|
|
||||||
|
High-performance server backend using [uSockets](https://github.com/uNetworking/uSockets) library.
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
Based on benchmark tests (200 connections, 100K requests):
|
||||||
|
|
||||||
|
| Backend | RPS | Avg Latency | P95 | P99 |
|
||||||
|
|---------|-----|-------------|-----|-----|
|
||||||
|
| uSockets | ~22,000 | 8.75ms | 16.66ms | 25.73ms |
|
||||||
|
| picoev | ~15,000 | 13.36ms | 18.89ms | 31.66ms |
|
||||||
|
|
||||||
|
**uSockets provides ~50% higher throughput under high concurrency.**
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```v
|
||||||
|
import hono
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
mut app := hono.Hono.new()
|
||||||
|
|
||||||
|
app.get('/', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('Hello from uSockets!')
|
||||||
|
})
|
||||||
|
|
||||||
|
// Use uSockets backend
|
||||||
|
app.listen_usockets(3000)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Build Command
|
||||||
|
|
||||||
|
```bash
|
||||||
|
v -enable-globals -cc gcc -ldflags "-ldbghelp" your_app.v -o app.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
**Required flags:**
|
||||||
|
- `-enable-globals` - Required for uSockets global state
|
||||||
|
- `-cc gcc` - Use GCC compiler (MinGW-w64 on Windows)
|
||||||
|
- `-ldflags "-ldbghelp"` - Fix Windows linking (Windows only)
|
||||||
|
|
||||||
|
## Prerequisites (Windows)
|
||||||
|
|
||||||
|
1. **GCC (MinGW-w64)**
|
||||||
|
```powershell
|
||||||
|
scoop install mingw
|
||||||
|
# or
|
||||||
|
choco install mingw
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **V Compiler** (0.4.x or later)
|
||||||
|
```powershell
|
||||||
|
scoop install vlang
|
||||||
|
```
|
||||||
|
|
||||||
|
## Directory Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
usockets/
|
||||||
|
├── include/ # Header files
|
||||||
|
│ ├── libusockets.h # uSockets API
|
||||||
|
│ ├── uv.h # libuv API
|
||||||
|
│ └── uv/ # libuv headers
|
||||||
|
├── lib/ # Pre-compiled libraries
|
||||||
|
│ ├── libusockets_full.a # uSockets + libuv (main)
|
||||||
|
│ ├── libuv.a # libuv static lib
|
||||||
|
│ └── ...
|
||||||
|
└── usockets.v # V bindings
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
```v
|
||||||
|
// Custom configuration
|
||||||
|
app.listen_usockets_with_config(hono.UsocketsConfig{
|
||||||
|
port: 8080
|
||||||
|
host: '0.0.0.0'
|
||||||
|
keepalive_timeout: 30
|
||||||
|
max_keepalive_req: 10000
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- On Windows, uSockets and picoev have similar performance
|
||||||
|
- On Linux, uSockets may have greater advantages due to epoll optimization
|
||||||
|
- uSockets excels under high concurrency (200+ connections)
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
/*
|
||||||
|
* Authored by Alex Hultman, 2018-2019.
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef LIBUSOCKETS_H
|
||||||
|
#define LIBUSOCKETS_H
|
||||||
|
|
||||||
|
/* 512kb shared receive buffer */
|
||||||
|
#ifndef LIBUS_RECV_BUFFER_LENGTH
|
||||||
|
#define LIBUS_RECV_BUFFER_LENGTH 524288
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* A timeout granularity of 4 seconds means give or take 4 seconds from set timeout */
|
||||||
|
#define LIBUS_TIMEOUT_GRANULARITY 4
|
||||||
|
/* 32 byte padding of receive buffer ends */
|
||||||
|
#define LIBUS_RECV_BUFFER_PADDING 32
|
||||||
|
/* Guaranteed alignment of extension memory */
|
||||||
|
#define LIBUS_EXT_ALIGNMENT 16
|
||||||
|
|
||||||
|
/* Define what a socket descriptor is based on platform */
|
||||||
|
#ifdef _WIN32
|
||||||
|
#ifndef NOMINMAX
|
||||||
|
#define NOMINMAX
|
||||||
|
#endif
|
||||||
|
#include <winsock2.h>
|
||||||
|
#define LIBUS_SOCKET_DESCRIPTOR SOCKET
|
||||||
|
#else
|
||||||
|
#define LIBUS_SOCKET_DESCRIPTOR int
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
enum {
|
||||||
|
/* No meaning, default listen option */
|
||||||
|
LIBUS_LISTEN_DEFAULT,
|
||||||
|
/* We exclusively own this port, do not share it */
|
||||||
|
LIBUS_LISTEN_EXCLUSIVE_PORT
|
||||||
|
};
|
||||||
|
|
||||||
|
/* Library types publicly available */
|
||||||
|
struct us_socket_t;
|
||||||
|
struct us_timer_t;
|
||||||
|
struct us_socket_context_t;
|
||||||
|
struct us_loop_t;
|
||||||
|
struct us_poll_t;
|
||||||
|
struct us_udp_socket_t;
|
||||||
|
struct us_udp_packet_buffer_t;
|
||||||
|
|
||||||
|
/* Extra for io_uring */
|
||||||
|
char *us_socket_send_buffer(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Public interface for UDP sockets */
|
||||||
|
|
||||||
|
/* Peeks data and length of UDP payload */
|
||||||
|
char *us_udp_packet_buffer_payload(struct us_udp_packet_buffer_t *buf, int index);
|
||||||
|
int us_udp_packet_buffer_payload_length(struct us_udp_packet_buffer_t *buf, int index);
|
||||||
|
|
||||||
|
/* Copies out local (received destination) ip (4 or 16 bytes) of received packet */
|
||||||
|
int us_udp_packet_buffer_local_ip(struct us_udp_packet_buffer_t *buf, int index, char *ip);
|
||||||
|
|
||||||
|
/* Get the bound port in host byte order */
|
||||||
|
int us_udp_socket_bound_port(struct us_udp_socket_t *s);
|
||||||
|
|
||||||
|
/* Peeks peer addr (sockaddr) of received packet */
|
||||||
|
char *us_udp_packet_buffer_peer(struct us_udp_packet_buffer_t *buf, int index);
|
||||||
|
|
||||||
|
/* Peeks ECN of received packet */
|
||||||
|
int us_udp_packet_buffer_ecn(struct us_udp_packet_buffer_t *buf, int index);
|
||||||
|
|
||||||
|
/* Receives a set of packets into specified packet buffer */
|
||||||
|
int us_udp_socket_receive(struct us_udp_socket_t *s, struct us_udp_packet_buffer_t *buf);
|
||||||
|
|
||||||
|
void us_udp_buffer_set_packet_payload(struct us_udp_packet_buffer_t *send_buf, int index, int offset, void *payload, int length, void *peer_addr);
|
||||||
|
|
||||||
|
int us_udp_socket_send(struct us_udp_socket_t *s, struct us_udp_packet_buffer_t *buf, int num);
|
||||||
|
|
||||||
|
/* Allocates a packet buffer that is reuable per thread. Mutated by us_udp_socket_receive. */
|
||||||
|
struct us_udp_packet_buffer_t *us_create_udp_packet_buffer();
|
||||||
|
|
||||||
|
/* Creates a (heavy-weight) UDP socket with a user space ring buffer. Again, this one is heavy weight and
|
||||||
|
* shoud be reused. One entire QUIC server can be implemented using only one single UDP socket so weight
|
||||||
|
* is not a concern as is the case for TCP sockets which are 1-to-1 with TCP connections. */
|
||||||
|
//struct us_udp_socket_t *us_create_udp_socket(struct us_loop_t *loop, void (*read_cb)(struct us_udp_socket_t *), unsigned short port);
|
||||||
|
|
||||||
|
//struct us_udp_socket_t *us_create_udp_socket(struct us_loop_t *loop, void (*data_cb)(struct us_udp_socket_t *, struct us_udp_packet_buffer_t *, int), void (*drain_cb)(struct us_udp_socket_t *), char *host, unsigned short port);
|
||||||
|
|
||||||
|
struct us_udp_socket_t *us_create_udp_socket(struct us_loop_t *loop, struct us_udp_packet_buffer_t *buf, void (*data_cb)(struct us_udp_socket_t *, struct us_udp_packet_buffer_t *, int), void (*drain_cb)(struct us_udp_socket_t *), const char *host, unsigned short port, void *user);
|
||||||
|
|
||||||
|
/* This one is ugly, should be ext! not user */
|
||||||
|
void *us_udp_socket_user(struct us_udp_socket_t *s);
|
||||||
|
|
||||||
|
/* Binds the UDP socket to an interface and port */
|
||||||
|
int us_udp_socket_bind(struct us_udp_socket_t *s, const char *hostname, unsigned int port);
|
||||||
|
|
||||||
|
/* Public interfaces for timers */
|
||||||
|
|
||||||
|
/* Create a new high precision, low performance timer. May fail and return null */
|
||||||
|
struct us_timer_t *us_create_timer(struct us_loop_t *loop, int fallthrough, unsigned int ext_size);
|
||||||
|
|
||||||
|
/* Returns user data extension for this timer */
|
||||||
|
void *us_timer_ext(struct us_timer_t *timer);
|
||||||
|
|
||||||
|
/* */
|
||||||
|
void us_timer_close(struct us_timer_t *timer);
|
||||||
|
|
||||||
|
/* Arm a timer with a delay from now and eventually a repeat delay.
|
||||||
|
* Specify 0 as repeat delay to disable repeating. Specify both 0 to disarm. */
|
||||||
|
void us_timer_set(struct us_timer_t *timer, void (*cb)(struct us_timer_t *t), int ms, int repeat_ms);
|
||||||
|
|
||||||
|
/* Returns the loop for this timer */
|
||||||
|
struct us_loop_t *us_timer_loop(struct us_timer_t *t);
|
||||||
|
|
||||||
|
/* Public interfaces for contexts */
|
||||||
|
|
||||||
|
struct us_socket_context_options_t {
|
||||||
|
const char *key_file_name;
|
||||||
|
const char *cert_file_name;
|
||||||
|
const char *passphrase;
|
||||||
|
const char *dh_params_file_name;
|
||||||
|
const char *ca_file_name;
|
||||||
|
const char *ssl_ciphers;
|
||||||
|
int ssl_prefer_low_memory_usage; /* Todo: rename to prefer_low_memory_usage and apply for TCP as well */
|
||||||
|
};
|
||||||
|
|
||||||
|
/* Return 15-bit timestamp for this context */
|
||||||
|
unsigned short us_socket_context_timestamp(int ssl, struct us_socket_context_t *context);
|
||||||
|
|
||||||
|
/* Adds SNI domain and cert in asn1 format */
|
||||||
|
void us_socket_context_add_server_name(int ssl, struct us_socket_context_t *context, const char *hostname_pattern, struct us_socket_context_options_t options, void *user);
|
||||||
|
void us_socket_context_remove_server_name(int ssl, struct us_socket_context_t *context, const char *hostname_pattern);
|
||||||
|
void us_socket_context_on_server_name(int ssl, struct us_socket_context_t *context, void (*cb)(struct us_socket_context_t *, const char *hostname));
|
||||||
|
void *us_socket_server_name_userdata(int ssl, struct us_socket_t *s);
|
||||||
|
void *us_socket_context_find_server_name_userdata(int ssl, struct us_socket_context_t *context, const char *hostname_pattern);
|
||||||
|
|
||||||
|
/* Returns the underlying SSL native handle, such as SSL_CTX or nullptr */
|
||||||
|
void *us_socket_context_get_native_handle(int ssl, struct us_socket_context_t *context);
|
||||||
|
|
||||||
|
/* A socket context holds shared callbacks and user data extension for associated sockets */
|
||||||
|
struct us_socket_context_t *us_create_socket_context(int ssl, struct us_loop_t *loop,
|
||||||
|
int ext_size, struct us_socket_context_options_t options);
|
||||||
|
|
||||||
|
/* Delete resources allocated at creation time. */
|
||||||
|
void us_socket_context_free(int ssl, struct us_socket_context_t *context);
|
||||||
|
|
||||||
|
/* Setters of various async callbacks */
|
||||||
|
void us_socket_context_on_pre_open(int ssl, struct us_socket_context_t *context,
|
||||||
|
LIBUS_SOCKET_DESCRIPTOR (*on_pre_open)(struct us_socket_context_t *context, LIBUS_SOCKET_DESCRIPTOR fd));
|
||||||
|
void us_socket_context_on_open(int ssl, struct us_socket_context_t *context,
|
||||||
|
struct us_socket_t *(*on_open)(struct us_socket_t *s, int is_client, char *ip, int ip_length));
|
||||||
|
void us_socket_context_on_close(int ssl, struct us_socket_context_t *context,
|
||||||
|
struct us_socket_t *(*on_close)(struct us_socket_t *s, int code, void *reason));
|
||||||
|
void us_socket_context_on_data(int ssl, struct us_socket_context_t *context,
|
||||||
|
struct us_socket_t *(*on_data)(struct us_socket_t *s, char *data, int length));
|
||||||
|
void us_socket_context_on_writable(int ssl, struct us_socket_context_t *context,
|
||||||
|
struct us_socket_t *(*on_writable)(struct us_socket_t *s));
|
||||||
|
void us_socket_context_on_timeout(int ssl, struct us_socket_context_t *context,
|
||||||
|
struct us_socket_t *(*on_timeout)(struct us_socket_t *s));
|
||||||
|
void us_socket_context_on_long_timeout(int ssl, struct us_socket_context_t *context,
|
||||||
|
struct us_socket_t *(*on_timeout)(struct us_socket_t *s));
|
||||||
|
/* This one is only used for when a connecting socket fails in a late stage. */
|
||||||
|
void us_socket_context_on_connect_error(int ssl, struct us_socket_context_t *context,
|
||||||
|
struct us_socket_t *(*on_connect_error)(struct us_socket_t *s, int code));
|
||||||
|
|
||||||
|
/* Emitted when a socket has been half-closed */
|
||||||
|
void us_socket_context_on_end(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_end)(struct us_socket_t *s));
|
||||||
|
|
||||||
|
/* Returns user data extension for this socket context */
|
||||||
|
void *us_socket_context_ext(int ssl, struct us_socket_context_t *context);
|
||||||
|
|
||||||
|
/* Closes all open sockets, including listen sockets. Does not invalidate the socket context. */
|
||||||
|
void us_socket_context_close(int ssl, struct us_socket_context_t *context);
|
||||||
|
|
||||||
|
/* Listen for connections. Acts as the main driving cog in a server. Will call set async callbacks. */
|
||||||
|
struct us_listen_socket_t *us_socket_context_listen(int ssl, struct us_socket_context_t *context,
|
||||||
|
const char *host, int port, int options, int socket_ext_size);
|
||||||
|
|
||||||
|
struct us_listen_socket_t *us_socket_context_listen_unix(int ssl, struct us_socket_context_t *context,
|
||||||
|
const char *path, int options, int socket_ext_size);
|
||||||
|
|
||||||
|
/* listen_socket.c/.h */
|
||||||
|
void us_listen_socket_close(int ssl, struct us_listen_socket_t *ls);
|
||||||
|
|
||||||
|
/* Adopt a socket which was accepted either internally, or from another accept() outside libusockets */
|
||||||
|
struct us_socket_t *us_adopt_accepted_socket(int ssl, struct us_socket_context_t *context, LIBUS_SOCKET_DESCRIPTOR client_fd,
|
||||||
|
unsigned int socket_ext_size, char *addr_ip, int addr_ip_length);
|
||||||
|
|
||||||
|
/* Land in on_open or on_connection_error or return null or return socket */
|
||||||
|
struct us_socket_t *us_socket_context_connect(int ssl, struct us_socket_context_t *context,
|
||||||
|
const char *host, int port, const char *source_host, int options, int socket_ext_size);
|
||||||
|
|
||||||
|
struct us_socket_t *us_socket_context_connect_unix(int ssl, struct us_socket_context_t *context,
|
||||||
|
const char *server_path, int options, int socket_ext_size);
|
||||||
|
|
||||||
|
/* Is this socket established? Can be used to check if a connecting socket has fired the on_open event yet.
|
||||||
|
* Can also be used to determine if a socket is a listen_socket or not, but you probably know that already. */
|
||||||
|
int us_socket_is_established(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Cancel a connecting socket. Can be used together with us_socket_timeout to limit connection times.
|
||||||
|
* Entirely destroys the socket - this function works like us_socket_close but does not trigger on_close event since
|
||||||
|
* you never got the on_open event first. */
|
||||||
|
struct us_socket_t *us_socket_close_connecting(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Returns the loop for this socket context. */
|
||||||
|
struct us_loop_t *us_socket_context_loop(int ssl, struct us_socket_context_t *context);
|
||||||
|
|
||||||
|
/* Invalidates passed socket, returning a new resized socket which belongs to a different socket context.
|
||||||
|
* Used mainly for "socket upgrades" such as when transitioning from HTTP to WebSocket. */
|
||||||
|
struct us_socket_t *us_socket_context_adopt_socket(int ssl, struct us_socket_context_t *context, struct us_socket_t *s, int ext_size);
|
||||||
|
|
||||||
|
/* Create a child socket context which acts much like its own socket context with its own callbacks yet still relies on the
|
||||||
|
* parent socket context for some shared resources. Child socket contexts should be used together with socket adoptions and nothing else. */
|
||||||
|
struct us_socket_context_t *us_create_child_socket_context(int ssl, struct us_socket_context_t *context, int context_ext_size);
|
||||||
|
|
||||||
|
/* Public interfaces for loops */
|
||||||
|
|
||||||
|
/* Returns a new event loop with user data extension */
|
||||||
|
struct us_loop_t *us_create_loop(void *hint, void (*wakeup_cb)(struct us_loop_t *loop),
|
||||||
|
void (*pre_cb)(struct us_loop_t *loop), void (*post_cb)(struct us_loop_t *loop), unsigned int ext_size);
|
||||||
|
|
||||||
|
/* Frees the loop immediately */
|
||||||
|
void us_loop_free(struct us_loop_t *loop);
|
||||||
|
|
||||||
|
/* Returns the loop user data extension */
|
||||||
|
void *us_loop_ext(struct us_loop_t *loop);
|
||||||
|
|
||||||
|
/* Blocks the calling thread and drives the event loop until no more non-fallthrough polls are scheduled */
|
||||||
|
void us_loop_run(struct us_loop_t *loop);
|
||||||
|
|
||||||
|
/* Signals the loop from any thread to wake up and execute its wakeup handler from the loop's own running thread.
|
||||||
|
* This is the only fully thread-safe function and serves as the basis for thread safety */
|
||||||
|
void us_wakeup_loop(struct us_loop_t *loop);
|
||||||
|
|
||||||
|
/* Hook up timers in existing loop */
|
||||||
|
void us_loop_integrate(struct us_loop_t *loop);
|
||||||
|
|
||||||
|
/* Returns the loop iteration number */
|
||||||
|
long long us_loop_iteration_number(struct us_loop_t *loop);
|
||||||
|
|
||||||
|
/* Public interfaces for polls */
|
||||||
|
|
||||||
|
/* A fallthrough poll does not keep the loop running, it falls through */
|
||||||
|
struct us_poll_t *us_create_poll(struct us_loop_t *loop, int fallthrough, unsigned int ext_size);
|
||||||
|
|
||||||
|
/* After stopping a poll you must manually free the memory */
|
||||||
|
void us_poll_free(struct us_poll_t *p, struct us_loop_t *loop);
|
||||||
|
|
||||||
|
/* Associate this poll with a socket descriptor and poll type */
|
||||||
|
void us_poll_init(struct us_poll_t *p, LIBUS_SOCKET_DESCRIPTOR fd, int poll_type);
|
||||||
|
|
||||||
|
/* Start, change and stop polling for events */
|
||||||
|
void us_poll_start(struct us_poll_t *p, struct us_loop_t *loop, int events);
|
||||||
|
void us_poll_change(struct us_poll_t *p, struct us_loop_t *loop, int events);
|
||||||
|
void us_poll_stop(struct us_poll_t *p, struct us_loop_t *loop);
|
||||||
|
|
||||||
|
/* Return what events we are polling for */
|
||||||
|
int us_poll_events(struct us_poll_t *p);
|
||||||
|
|
||||||
|
/* Returns the user data extension of this poll */
|
||||||
|
void *us_poll_ext(struct us_poll_t *p);
|
||||||
|
|
||||||
|
/* Get associated socket descriptor from a poll */
|
||||||
|
LIBUS_SOCKET_DESCRIPTOR us_poll_fd(struct us_poll_t *p);
|
||||||
|
|
||||||
|
/* Resize an active poll */
|
||||||
|
struct us_poll_t *us_poll_resize(struct us_poll_t *p, struct us_loop_t *loop, unsigned int ext_size);
|
||||||
|
|
||||||
|
/* Public interfaces for sockets */
|
||||||
|
|
||||||
|
/* Returns the underlying native handle for a socket, such as SSL or file descriptor.
|
||||||
|
* In the case of file descriptor, the value of pointer is fd. */
|
||||||
|
void *us_socket_get_native_handle(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Write up to length bytes of data. Returns actual bytes written.
|
||||||
|
* Will call the on_writable callback of active socket context on failure to write everything off in one go.
|
||||||
|
* Set hint msg_more if you have more immediate data to write. */
|
||||||
|
int us_socket_write(int ssl, struct us_socket_t *s, const char *data, int length, int msg_more);
|
||||||
|
|
||||||
|
/* Special path for non-SSL sockets. Used to send header and payload in one go. Works like us_socket_write. */
|
||||||
|
int us_socket_write2(int ssl, struct us_socket_t *s, const char *header, int header_length, const char *payload, int payload_length);
|
||||||
|
|
||||||
|
/* Set a low precision, high performance timer on a socket. A socket can only have one single active timer
|
||||||
|
* at any given point in time. Will remove any such pre set timer */
|
||||||
|
void us_socket_timeout(int ssl, struct us_socket_t *s, unsigned int seconds);
|
||||||
|
|
||||||
|
/* Set a low precision, high performance timer on a socket. Suitable for per-minute precision. */
|
||||||
|
void us_socket_long_timeout(int ssl, struct us_socket_t *s, unsigned int minutes);
|
||||||
|
|
||||||
|
/* Return the user data extension of this socket */
|
||||||
|
void *us_socket_ext(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Return the socket context of this socket */
|
||||||
|
struct us_socket_context_t *us_socket_context(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Withdraw any msg_more status and flush any pending data */
|
||||||
|
void us_socket_flush(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Shuts down the connection by sending FIN and/or close_notify */
|
||||||
|
void us_socket_shutdown(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Shuts down the connection in terms of read, meaning next event loop
|
||||||
|
* iteration will catch the socket being closed. Can be used to defer closing
|
||||||
|
* to next event loop iteration. */
|
||||||
|
void us_socket_shutdown_read(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Returns whether the socket has been shut down or not */
|
||||||
|
int us_socket_is_shut_down(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Returns whether this socket has been closed. Only valid if memory has not yet been released. */
|
||||||
|
int us_socket_is_closed(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Immediately closes the socket */
|
||||||
|
struct us_socket_t *us_socket_close(int ssl, struct us_socket_t *s, int code, void *reason);
|
||||||
|
|
||||||
|
/* Returns local port or -1 on failure. */
|
||||||
|
int us_socket_local_port(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Returns remote ephemeral port or -1 on failure. */
|
||||||
|
int us_socket_remote_port(int ssl, struct us_socket_t *s);
|
||||||
|
|
||||||
|
/* Copy remote (IP) address of socket, or fail with zero length. */
|
||||||
|
void us_socket_remote_address(int ssl, struct us_socket_t *s, char *buf, int *length);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Decide what eventing system to use by default */
|
||||||
|
#if !defined(LIBUS_USE_IO_URING) && !defined(LIBUS_USE_EPOLL) && !defined(LIBUS_USE_LIBUV) && !defined(LIBUS_USE_GCD) && !defined(LIBUS_USE_KQUEUE) && !defined(LIBUS_USE_ASIO)
|
||||||
|
#if defined(_WIN32)
|
||||||
|
#define LIBUS_USE_LIBUV
|
||||||
|
#elif defined(__APPLE__) || defined(__FreeBSD__)
|
||||||
|
#define LIBUS_USE_KQUEUE
|
||||||
|
#else
|
||||||
|
#define LIBUS_USE_EPOLL
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif // LIBUSOCKETS_H
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_AIX_H
|
||||||
|
#define UV_AIX_H
|
||||||
|
|
||||||
|
#define UV_PLATFORM_LOOP_FIELDS \
|
||||||
|
int fs_fd; \
|
||||||
|
|
||||||
|
#define UV_PLATFORM_FS_EVENT_FIELDS \
|
||||||
|
uv__io_t event_watcher; \
|
||||||
|
char *dir_filename; \
|
||||||
|
|
||||||
|
#endif /* UV_AIX_H */
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_BSD_H
|
||||||
|
#define UV_BSD_H
|
||||||
|
|
||||||
|
#define UV_PLATFORM_FS_EVENT_FIELDS \
|
||||||
|
uv__io_t event_watcher; \
|
||||||
|
|
||||||
|
#define UV_IO_PRIVATE_PLATFORM_FIELDS \
|
||||||
|
int rcount; \
|
||||||
|
int wcount; \
|
||||||
|
|
||||||
|
#define UV_HAVE_KQUEUE 1
|
||||||
|
|
||||||
|
#endif /* UV_BSD_H */
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_DARWIN_H
|
||||||
|
#define UV_DARWIN_H
|
||||||
|
|
||||||
|
#if defined(__APPLE__) && defined(__MACH__)
|
||||||
|
# include <mach/mach.h>
|
||||||
|
# include <mach/task.h>
|
||||||
|
# include <mach/semaphore.h>
|
||||||
|
# include <TargetConditionals.h>
|
||||||
|
# define UV_PLATFORM_SEM_T semaphore_t
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define UV_IO_PRIVATE_PLATFORM_FIELDS \
|
||||||
|
int rcount; \
|
||||||
|
int wcount; \
|
||||||
|
|
||||||
|
#define UV_PLATFORM_LOOP_FIELDS \
|
||||||
|
uv_thread_t cf_thread; \
|
||||||
|
void* _cf_reserved; \
|
||||||
|
void* cf_state; \
|
||||||
|
uv_mutex_t cf_mutex; \
|
||||||
|
uv_sem_t cf_sem; \
|
||||||
|
struct uv__queue cf_signals; \
|
||||||
|
|
||||||
|
#define UV_PLATFORM_FS_EVENT_FIELDS \
|
||||||
|
uv__io_t event_watcher; \
|
||||||
|
char* realpath; \
|
||||||
|
int realpath_len; \
|
||||||
|
int cf_flags; \
|
||||||
|
uv_async_t* cf_cb; \
|
||||||
|
struct uv__queue cf_events; \
|
||||||
|
struct uv__queue cf_member; \
|
||||||
|
int cf_error; \
|
||||||
|
uv_mutex_t cf_mutex; \
|
||||||
|
|
||||||
|
#define UV_STREAM_PRIVATE_PLATFORM_FIELDS \
|
||||||
|
void* select; \
|
||||||
|
|
||||||
|
#define UV_HAVE_KQUEUE 1
|
||||||
|
|
||||||
|
#endif /* UV_DARWIN_H */
|
||||||
@@ -0,0 +1,483 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_ERRNO_H_
|
||||||
|
#define UV_ERRNO_H_
|
||||||
|
|
||||||
|
#include <errno.h>
|
||||||
|
#if EDOM > 0
|
||||||
|
# define UV__ERR(x) (-(x))
|
||||||
|
#else
|
||||||
|
# define UV__ERR(x) (x)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define UV__EOF (-4095)
|
||||||
|
#define UV__UNKNOWN (-4094)
|
||||||
|
|
||||||
|
#define UV__EAI_ADDRFAMILY (-3000)
|
||||||
|
#define UV__EAI_AGAIN (-3001)
|
||||||
|
#define UV__EAI_BADFLAGS (-3002)
|
||||||
|
#define UV__EAI_CANCELED (-3003)
|
||||||
|
#define UV__EAI_FAIL (-3004)
|
||||||
|
#define UV__EAI_FAMILY (-3005)
|
||||||
|
#define UV__EAI_MEMORY (-3006)
|
||||||
|
#define UV__EAI_NODATA (-3007)
|
||||||
|
#define UV__EAI_NONAME (-3008)
|
||||||
|
#define UV__EAI_OVERFLOW (-3009)
|
||||||
|
#define UV__EAI_SERVICE (-3010)
|
||||||
|
#define UV__EAI_SOCKTYPE (-3011)
|
||||||
|
#define UV__EAI_BADHINTS (-3013)
|
||||||
|
#define UV__EAI_PROTOCOL (-3014)
|
||||||
|
|
||||||
|
/* Only map to the system errno on non-Windows platforms. It's apparently
|
||||||
|
* a fairly common practice for Windows programmers to redefine errno codes.
|
||||||
|
*/
|
||||||
|
#if defined(E2BIG) && !defined(_WIN32)
|
||||||
|
# define UV__E2BIG UV__ERR(E2BIG)
|
||||||
|
#else
|
||||||
|
# define UV__E2BIG (-4093)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EACCES) && !defined(_WIN32)
|
||||||
|
# define UV__EACCES UV__ERR(EACCES)
|
||||||
|
#else
|
||||||
|
# define UV__EACCES (-4092)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EADDRINUSE) && !defined(_WIN32)
|
||||||
|
# define UV__EADDRINUSE UV__ERR(EADDRINUSE)
|
||||||
|
#else
|
||||||
|
# define UV__EADDRINUSE (-4091)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EADDRNOTAVAIL) && !defined(_WIN32)
|
||||||
|
# define UV__EADDRNOTAVAIL UV__ERR(EADDRNOTAVAIL)
|
||||||
|
#else
|
||||||
|
# define UV__EADDRNOTAVAIL (-4090)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EAFNOSUPPORT) && !defined(_WIN32)
|
||||||
|
# define UV__EAFNOSUPPORT UV__ERR(EAFNOSUPPORT)
|
||||||
|
#else
|
||||||
|
# define UV__EAFNOSUPPORT (-4089)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EAGAIN) && !defined(_WIN32)
|
||||||
|
# define UV__EAGAIN UV__ERR(EAGAIN)
|
||||||
|
#else
|
||||||
|
# define UV__EAGAIN (-4088)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EALREADY) && !defined(_WIN32)
|
||||||
|
# define UV__EALREADY UV__ERR(EALREADY)
|
||||||
|
#else
|
||||||
|
# define UV__EALREADY (-4084)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EBADF) && !defined(_WIN32)
|
||||||
|
# define UV__EBADF UV__ERR(EBADF)
|
||||||
|
#else
|
||||||
|
# define UV__EBADF (-4083)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EBUSY) && !defined(_WIN32)
|
||||||
|
# define UV__EBUSY UV__ERR(EBUSY)
|
||||||
|
#else
|
||||||
|
# define UV__EBUSY (-4082)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ECANCELED) && !defined(_WIN32)
|
||||||
|
# define UV__ECANCELED UV__ERR(ECANCELED)
|
||||||
|
#else
|
||||||
|
# define UV__ECANCELED (-4081)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ECHARSET) && !defined(_WIN32)
|
||||||
|
# define UV__ECHARSET UV__ERR(ECHARSET)
|
||||||
|
#else
|
||||||
|
# define UV__ECHARSET (-4080)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ECONNABORTED) && !defined(_WIN32)
|
||||||
|
# define UV__ECONNABORTED UV__ERR(ECONNABORTED)
|
||||||
|
#else
|
||||||
|
# define UV__ECONNABORTED (-4079)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ECONNREFUSED) && !defined(_WIN32)
|
||||||
|
# define UV__ECONNREFUSED UV__ERR(ECONNREFUSED)
|
||||||
|
#else
|
||||||
|
# define UV__ECONNREFUSED (-4078)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ECONNRESET) && !defined(_WIN32)
|
||||||
|
# define UV__ECONNRESET UV__ERR(ECONNRESET)
|
||||||
|
#else
|
||||||
|
# define UV__ECONNRESET (-4077)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EDESTADDRREQ) && !defined(_WIN32)
|
||||||
|
# define UV__EDESTADDRREQ UV__ERR(EDESTADDRREQ)
|
||||||
|
#else
|
||||||
|
# define UV__EDESTADDRREQ (-4076)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EEXIST) && !defined(_WIN32)
|
||||||
|
# define UV__EEXIST UV__ERR(EEXIST)
|
||||||
|
#else
|
||||||
|
# define UV__EEXIST (-4075)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EFAULT) && !defined(_WIN32)
|
||||||
|
# define UV__EFAULT UV__ERR(EFAULT)
|
||||||
|
#else
|
||||||
|
# define UV__EFAULT (-4074)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EHOSTUNREACH) && !defined(_WIN32)
|
||||||
|
# define UV__EHOSTUNREACH UV__ERR(EHOSTUNREACH)
|
||||||
|
#else
|
||||||
|
# define UV__EHOSTUNREACH (-4073)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EINTR) && !defined(_WIN32)
|
||||||
|
# define UV__EINTR UV__ERR(EINTR)
|
||||||
|
#else
|
||||||
|
# define UV__EINTR (-4072)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EINVAL) && !defined(_WIN32)
|
||||||
|
# define UV__EINVAL UV__ERR(EINVAL)
|
||||||
|
#else
|
||||||
|
# define UV__EINVAL (-4071)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EIO) && !defined(_WIN32)
|
||||||
|
# define UV__EIO UV__ERR(EIO)
|
||||||
|
#else
|
||||||
|
# define UV__EIO (-4070)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EISCONN) && !defined(_WIN32)
|
||||||
|
# define UV__EISCONN UV__ERR(EISCONN)
|
||||||
|
#else
|
||||||
|
# define UV__EISCONN (-4069)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EISDIR) && !defined(_WIN32)
|
||||||
|
# define UV__EISDIR UV__ERR(EISDIR)
|
||||||
|
#else
|
||||||
|
# define UV__EISDIR (-4068)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ELOOP) && !defined(_WIN32)
|
||||||
|
# define UV__ELOOP UV__ERR(ELOOP)
|
||||||
|
#else
|
||||||
|
# define UV__ELOOP (-4067)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EMFILE) && !defined(_WIN32)
|
||||||
|
# define UV__EMFILE UV__ERR(EMFILE)
|
||||||
|
#else
|
||||||
|
# define UV__EMFILE (-4066)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EMSGSIZE) && !defined(_WIN32)
|
||||||
|
# define UV__EMSGSIZE UV__ERR(EMSGSIZE)
|
||||||
|
#else
|
||||||
|
# define UV__EMSGSIZE (-4065)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENAMETOOLONG) && !defined(_WIN32)
|
||||||
|
# define UV__ENAMETOOLONG UV__ERR(ENAMETOOLONG)
|
||||||
|
#else
|
||||||
|
# define UV__ENAMETOOLONG (-4064)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENETDOWN) && !defined(_WIN32)
|
||||||
|
# define UV__ENETDOWN UV__ERR(ENETDOWN)
|
||||||
|
#else
|
||||||
|
# define UV__ENETDOWN (-4063)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENETUNREACH) && !defined(_WIN32)
|
||||||
|
# define UV__ENETUNREACH UV__ERR(ENETUNREACH)
|
||||||
|
#else
|
||||||
|
# define UV__ENETUNREACH (-4062)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENFILE) && !defined(_WIN32)
|
||||||
|
# define UV__ENFILE UV__ERR(ENFILE)
|
||||||
|
#else
|
||||||
|
# define UV__ENFILE (-4061)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOBUFS) && !defined(_WIN32)
|
||||||
|
# define UV__ENOBUFS UV__ERR(ENOBUFS)
|
||||||
|
#else
|
||||||
|
# define UV__ENOBUFS (-4060)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENODEV) && !defined(_WIN32)
|
||||||
|
# define UV__ENODEV UV__ERR(ENODEV)
|
||||||
|
#else
|
||||||
|
# define UV__ENODEV (-4059)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOENT) && !defined(_WIN32)
|
||||||
|
# define UV__ENOENT UV__ERR(ENOENT)
|
||||||
|
#else
|
||||||
|
# define UV__ENOENT (-4058)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOMEM) && !defined(_WIN32)
|
||||||
|
# define UV__ENOMEM UV__ERR(ENOMEM)
|
||||||
|
#else
|
||||||
|
# define UV__ENOMEM (-4057)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENONET) && !defined(_WIN32)
|
||||||
|
# define UV__ENONET UV__ERR(ENONET)
|
||||||
|
#else
|
||||||
|
# define UV__ENONET (-4056)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOSPC) && !defined(_WIN32)
|
||||||
|
# define UV__ENOSPC UV__ERR(ENOSPC)
|
||||||
|
#else
|
||||||
|
# define UV__ENOSPC (-4055)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOSYS) && !defined(_WIN32)
|
||||||
|
# define UV__ENOSYS UV__ERR(ENOSYS)
|
||||||
|
#else
|
||||||
|
# define UV__ENOSYS (-4054)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOTCONN) && !defined(_WIN32)
|
||||||
|
# define UV__ENOTCONN UV__ERR(ENOTCONN)
|
||||||
|
#else
|
||||||
|
# define UV__ENOTCONN (-4053)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOTDIR) && !defined(_WIN32)
|
||||||
|
# define UV__ENOTDIR UV__ERR(ENOTDIR)
|
||||||
|
#else
|
||||||
|
# define UV__ENOTDIR (-4052)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOTEMPTY) && !defined(_WIN32)
|
||||||
|
# define UV__ENOTEMPTY UV__ERR(ENOTEMPTY)
|
||||||
|
#else
|
||||||
|
# define UV__ENOTEMPTY (-4051)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOTSOCK) && !defined(_WIN32)
|
||||||
|
# define UV__ENOTSOCK UV__ERR(ENOTSOCK)
|
||||||
|
#else
|
||||||
|
# define UV__ENOTSOCK (-4050)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOTSUP) && !defined(_WIN32)
|
||||||
|
# define UV__ENOTSUP UV__ERR(ENOTSUP)
|
||||||
|
#else
|
||||||
|
# define UV__ENOTSUP (-4049)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EPERM) && !defined(_WIN32)
|
||||||
|
# define UV__EPERM UV__ERR(EPERM)
|
||||||
|
#else
|
||||||
|
# define UV__EPERM (-4048)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EPIPE) && !defined(_WIN32)
|
||||||
|
# define UV__EPIPE UV__ERR(EPIPE)
|
||||||
|
#else
|
||||||
|
# define UV__EPIPE (-4047)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EPROTO) && !defined(_WIN32)
|
||||||
|
# define UV__EPROTO UV__ERR(EPROTO)
|
||||||
|
#else
|
||||||
|
# define UV__EPROTO (-4046)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EPROTONOSUPPORT) && !defined(_WIN32)
|
||||||
|
# define UV__EPROTONOSUPPORT UV__ERR(EPROTONOSUPPORT)
|
||||||
|
#else
|
||||||
|
# define UV__EPROTONOSUPPORT (-4045)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EPROTOTYPE) && !defined(_WIN32)
|
||||||
|
# define UV__EPROTOTYPE UV__ERR(EPROTOTYPE)
|
||||||
|
#else
|
||||||
|
# define UV__EPROTOTYPE (-4044)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EROFS) && !defined(_WIN32)
|
||||||
|
# define UV__EROFS UV__ERR(EROFS)
|
||||||
|
#else
|
||||||
|
# define UV__EROFS (-4043)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ESHUTDOWN) && !defined(_WIN32)
|
||||||
|
# define UV__ESHUTDOWN UV__ERR(ESHUTDOWN)
|
||||||
|
#else
|
||||||
|
# define UV__ESHUTDOWN (-4042)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ESPIPE) && !defined(_WIN32)
|
||||||
|
# define UV__ESPIPE UV__ERR(ESPIPE)
|
||||||
|
#else
|
||||||
|
# define UV__ESPIPE (-4041)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ESRCH) && !defined(_WIN32)
|
||||||
|
# define UV__ESRCH UV__ERR(ESRCH)
|
||||||
|
#else
|
||||||
|
# define UV__ESRCH (-4040)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ETIMEDOUT) && !defined(_WIN32)
|
||||||
|
# define UV__ETIMEDOUT UV__ERR(ETIMEDOUT)
|
||||||
|
#else
|
||||||
|
# define UV__ETIMEDOUT (-4039)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ETXTBSY) && !defined(_WIN32)
|
||||||
|
# define UV__ETXTBSY UV__ERR(ETXTBSY)
|
||||||
|
#else
|
||||||
|
# define UV__ETXTBSY (-4038)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EXDEV) && !defined(_WIN32)
|
||||||
|
# define UV__EXDEV UV__ERR(EXDEV)
|
||||||
|
#else
|
||||||
|
# define UV__EXDEV (-4037)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EFBIG) && !defined(_WIN32)
|
||||||
|
# define UV__EFBIG UV__ERR(EFBIG)
|
||||||
|
#else
|
||||||
|
# define UV__EFBIG (-4036)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOPROTOOPT) && !defined(_WIN32)
|
||||||
|
# define UV__ENOPROTOOPT UV__ERR(ENOPROTOOPT)
|
||||||
|
#else
|
||||||
|
# define UV__ENOPROTOOPT (-4035)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ERANGE) && !defined(_WIN32)
|
||||||
|
# define UV__ERANGE UV__ERR(ERANGE)
|
||||||
|
#else
|
||||||
|
# define UV__ERANGE (-4034)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENXIO) && !defined(_WIN32)
|
||||||
|
# define UV__ENXIO UV__ERR(ENXIO)
|
||||||
|
#else
|
||||||
|
# define UV__ENXIO (-4033)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EMLINK) && !defined(_WIN32)
|
||||||
|
# define UV__EMLINK UV__ERR(EMLINK)
|
||||||
|
#else
|
||||||
|
# define UV__EMLINK (-4032)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* EHOSTDOWN is not visible on BSD-like systems when _POSIX_C_SOURCE is
|
||||||
|
* defined. Fortunately, its value is always 64 so it's possible albeit
|
||||||
|
* icky to hard-code it.
|
||||||
|
*/
|
||||||
|
#if defined(EHOSTDOWN) && !defined(_WIN32)
|
||||||
|
# define UV__EHOSTDOWN UV__ERR(EHOSTDOWN)
|
||||||
|
#elif defined(__APPLE__) || \
|
||||||
|
defined(__DragonFly__) || \
|
||||||
|
defined(__FreeBSD__) || \
|
||||||
|
defined(__NetBSD__) || \
|
||||||
|
defined(__OpenBSD__)
|
||||||
|
# define UV__EHOSTDOWN (-64)
|
||||||
|
#else
|
||||||
|
# define UV__EHOSTDOWN (-4031)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EREMOTEIO) && !defined(_WIN32)
|
||||||
|
# define UV__EREMOTEIO UV__ERR(EREMOTEIO)
|
||||||
|
#else
|
||||||
|
# define UV__EREMOTEIO (-4030)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOTTY) && !defined(_WIN32)
|
||||||
|
# define UV__ENOTTY UV__ERR(ENOTTY)
|
||||||
|
#else
|
||||||
|
# define UV__ENOTTY (-4029)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EFTYPE) && !defined(_WIN32)
|
||||||
|
# define UV__EFTYPE UV__ERR(EFTYPE)
|
||||||
|
#else
|
||||||
|
# define UV__EFTYPE (-4028)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EILSEQ) && !defined(_WIN32)
|
||||||
|
# define UV__EILSEQ UV__ERR(EILSEQ)
|
||||||
|
#else
|
||||||
|
# define UV__EILSEQ (-4027)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EOVERFLOW) && !defined(_WIN32)
|
||||||
|
# define UV__EOVERFLOW UV__ERR(EOVERFLOW)
|
||||||
|
#else
|
||||||
|
# define UV__EOVERFLOW (-4026)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ESOCKTNOSUPPORT) && !defined(_WIN32)
|
||||||
|
# define UV__ESOCKTNOSUPPORT UV__ERR(ESOCKTNOSUPPORT)
|
||||||
|
#else
|
||||||
|
# define UV__ESOCKTNOSUPPORT (-4025)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* FreeBSD defines ENODATA in /usr/include/c++/v1/errno.h which is only visible
|
||||||
|
* if C++ is being used. Define it directly to avoid problems when integrating
|
||||||
|
* libuv in a C++ project.
|
||||||
|
*/
|
||||||
|
#if defined(ENODATA) && !defined(_WIN32)
|
||||||
|
# define UV__ENODATA UV__ERR(ENODATA)
|
||||||
|
#elif defined(__FreeBSD__)
|
||||||
|
# define UV__ENODATA (-9919)
|
||||||
|
#else
|
||||||
|
# define UV__ENODATA (-4024)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(EUNATCH) && !defined(_WIN32)
|
||||||
|
# define UV__EUNATCH UV__ERR(EUNATCH)
|
||||||
|
#else
|
||||||
|
# define UV__EUNATCH (-4023)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(ENOEXEC) && !defined(_WIN32)
|
||||||
|
# define UV__ENOEXEC UV__ERR(ENOEXEC)
|
||||||
|
#else
|
||||||
|
# define UV__ENOEXEC (-4022)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* UV_ERRNO_H_ */
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_LINUX_H
|
||||||
|
#define UV_LINUX_H
|
||||||
|
|
||||||
|
#define UV_PLATFORM_LOOP_FIELDS \
|
||||||
|
uv__io_t inotify_read_watcher; \
|
||||||
|
void* inotify_watchers; \
|
||||||
|
int inotify_fd; \
|
||||||
|
|
||||||
|
#define UV_PLATFORM_FS_EVENT_FIELDS \
|
||||||
|
struct uv__queue watchers; \
|
||||||
|
int wd; \
|
||||||
|
|
||||||
|
#endif /* UV_LINUX_H */
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/* Copyright libuv project contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_MVS_H
|
||||||
|
#define UV_MVS_H
|
||||||
|
|
||||||
|
#define UV_PLATFORM_SEM_T long
|
||||||
|
|
||||||
|
#define UV_PLATFORM_LOOP_FIELDS \
|
||||||
|
void* ep; \
|
||||||
|
|
||||||
|
#define UV_PLATFORM_FS_EVENT_FIELDS \
|
||||||
|
char rfis_rftok[8]; \
|
||||||
|
|
||||||
|
#endif /* UV_MVS_H */
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/* Copyright libuv project contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_POSIX_H
|
||||||
|
#define UV_POSIX_H
|
||||||
|
|
||||||
|
#define UV_PLATFORM_LOOP_FIELDS \
|
||||||
|
struct pollfd* poll_fds; \
|
||||||
|
size_t poll_fds_used; \
|
||||||
|
size_t poll_fds_size; \
|
||||||
|
unsigned char poll_fds_iterating; \
|
||||||
|
|
||||||
|
#endif /* UV_POSIX_H */
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_SUNOS_H
|
||||||
|
#define UV_SUNOS_H
|
||||||
|
|
||||||
|
#include <sys/port.h>
|
||||||
|
#include <port.h>
|
||||||
|
|
||||||
|
/* For the sake of convenience and reduced #ifdef-ery in src/unix/sunos.c,
|
||||||
|
* add the fs_event fields even when this version of SunOS doesn't support
|
||||||
|
* file watching.
|
||||||
|
*/
|
||||||
|
#define UV_PLATFORM_LOOP_FIELDS \
|
||||||
|
uv__io_t fs_event_watcher; \
|
||||||
|
int fs_fd; \
|
||||||
|
|
||||||
|
#if defined(PORT_SOURCE_FILE)
|
||||||
|
|
||||||
|
# define UV_PLATFORM_FS_EVENT_FIELDS \
|
||||||
|
file_obj_t fo; \
|
||||||
|
int fd; \
|
||||||
|
|
||||||
|
#endif /* defined(PORT_SOURCE_FILE) */
|
||||||
|
|
||||||
|
#endif /* UV_SUNOS_H */
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is private to libuv. It provides common functionality to both
|
||||||
|
* Windows and Unix backends.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_THREADPOOL_H_
|
||||||
|
#define UV_THREADPOOL_H_
|
||||||
|
|
||||||
|
struct uv__work {
|
||||||
|
void (*work)(struct uv__work *w);
|
||||||
|
void (*done)(struct uv__work *w, int status);
|
||||||
|
struct uv_loop_s* loop;
|
||||||
|
struct uv__queue wq;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif /* UV_THREADPOOL_H_ */
|
||||||
@@ -0,0 +1,521 @@
|
|||||||
|
/*-
|
||||||
|
* Copyright 2002 Niels Provos <provos@citi.umich.edu>
|
||||||
|
* All rights reserved.
|
||||||
|
*
|
||||||
|
* Redistribution and use in source and binary forms, with or without
|
||||||
|
* modification, are permitted provided that the following conditions
|
||||||
|
* are met:
|
||||||
|
* 1. Redistributions of source code must retain the above copyright
|
||||||
|
* notice, this list of conditions and the following disclaimer.
|
||||||
|
* 2. Redistributions in binary form must reproduce the above copyright
|
||||||
|
* notice, this list of conditions and the following disclaimer in the
|
||||||
|
* documentation and/or other materials provided with the distribution.
|
||||||
|
*
|
||||||
|
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||||
|
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||||
|
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||||
|
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||||
|
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||||
|
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||||
|
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_TREE_H_
|
||||||
|
#define UV_TREE_H_
|
||||||
|
|
||||||
|
#ifndef UV__UNUSED
|
||||||
|
# if __GNUC__
|
||||||
|
# define UV__UNUSED __attribute__((unused))
|
||||||
|
# else
|
||||||
|
# define UV__UNUSED
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file defines data structures for red-black trees.
|
||||||
|
* A red-black tree is a binary search tree with the node color as an
|
||||||
|
* extra attribute. It fulfills a set of conditions:
|
||||||
|
* - every search path from the root to a leaf consists of the
|
||||||
|
* same number of black nodes,
|
||||||
|
* - each red node (except for the root) has a black parent,
|
||||||
|
* - each leaf node is black.
|
||||||
|
*
|
||||||
|
* Every operation on a red-black tree is bounded as O(lg n).
|
||||||
|
* The maximum height of a red-black tree is 2lg (n+1).
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Macros that define a red-black tree */
|
||||||
|
#define RB_HEAD(name, type) \
|
||||||
|
struct name { \
|
||||||
|
struct type *rbh_root; /* root of the tree */ \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define RB_INITIALIZER(root) \
|
||||||
|
{ NULL }
|
||||||
|
|
||||||
|
#define RB_INIT(root) do { \
|
||||||
|
(root)->rbh_root = NULL; \
|
||||||
|
} while (/*CONSTCOND*/ 0)
|
||||||
|
|
||||||
|
#define RB_BLACK 0
|
||||||
|
#define RB_RED 1
|
||||||
|
#define RB_ENTRY(type) \
|
||||||
|
struct { \
|
||||||
|
struct type *rbe_left; /* left element */ \
|
||||||
|
struct type *rbe_right; /* right element */ \
|
||||||
|
struct type *rbe_parent; /* parent element */ \
|
||||||
|
int rbe_color; /* node color */ \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define RB_LEFT(elm, field) (elm)->field.rbe_left
|
||||||
|
#define RB_RIGHT(elm, field) (elm)->field.rbe_right
|
||||||
|
#define RB_PARENT(elm, field) (elm)->field.rbe_parent
|
||||||
|
#define RB_COLOR(elm, field) (elm)->field.rbe_color
|
||||||
|
#define RB_ROOT(head) (head)->rbh_root
|
||||||
|
#define RB_EMPTY(head) (RB_ROOT(head) == NULL)
|
||||||
|
|
||||||
|
#define RB_SET(elm, parent, field) do { \
|
||||||
|
RB_PARENT(elm, field) = parent; \
|
||||||
|
RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \
|
||||||
|
RB_COLOR(elm, field) = RB_RED; \
|
||||||
|
} while (/*CONSTCOND*/ 0)
|
||||||
|
|
||||||
|
#define RB_SET_BLACKRED(black, red, field) do { \
|
||||||
|
RB_COLOR(black, field) = RB_BLACK; \
|
||||||
|
RB_COLOR(red, field) = RB_RED; \
|
||||||
|
} while (/*CONSTCOND*/ 0)
|
||||||
|
|
||||||
|
#ifndef RB_AUGMENT
|
||||||
|
#define RB_AUGMENT(x) do {} while (0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \
|
||||||
|
(tmp) = RB_RIGHT(elm, field); \
|
||||||
|
if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field)) != NULL) { \
|
||||||
|
RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \
|
||||||
|
} \
|
||||||
|
RB_AUGMENT(elm); \
|
||||||
|
if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
|
||||||
|
if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
|
||||||
|
RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
|
||||||
|
else \
|
||||||
|
RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
|
||||||
|
} else \
|
||||||
|
(head)->rbh_root = (tmp); \
|
||||||
|
RB_LEFT(tmp, field) = (elm); \
|
||||||
|
RB_PARENT(elm, field) = (tmp); \
|
||||||
|
RB_AUGMENT(tmp); \
|
||||||
|
if ((RB_PARENT(tmp, field))) \
|
||||||
|
RB_AUGMENT(RB_PARENT(tmp, field)); \
|
||||||
|
} while (/*CONSTCOND*/ 0)
|
||||||
|
|
||||||
|
#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \
|
||||||
|
(tmp) = RB_LEFT(elm, field); \
|
||||||
|
if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field)) != NULL) { \
|
||||||
|
RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \
|
||||||
|
} \
|
||||||
|
RB_AUGMENT(elm); \
|
||||||
|
if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
|
||||||
|
if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
|
||||||
|
RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
|
||||||
|
else \
|
||||||
|
RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
|
||||||
|
} else \
|
||||||
|
(head)->rbh_root = (tmp); \
|
||||||
|
RB_RIGHT(tmp, field) = (elm); \
|
||||||
|
RB_PARENT(elm, field) = (tmp); \
|
||||||
|
RB_AUGMENT(tmp); \
|
||||||
|
if ((RB_PARENT(tmp, field))) \
|
||||||
|
RB_AUGMENT(RB_PARENT(tmp, field)); \
|
||||||
|
} while (/*CONSTCOND*/ 0)
|
||||||
|
|
||||||
|
/* Generates prototypes and inline functions */
|
||||||
|
#define RB_PROTOTYPE(name, type, field, cmp) \
|
||||||
|
RB_PROTOTYPE_INTERNAL(name, type, field, cmp,)
|
||||||
|
#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \
|
||||||
|
RB_PROTOTYPE_INTERNAL(name, type, field, cmp, UV__UNUSED static)
|
||||||
|
#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \
|
||||||
|
attr void name##_RB_INSERT_COLOR(struct name *, struct type *); \
|
||||||
|
attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
|
||||||
|
attr struct type *name##_RB_REMOVE(struct name *, struct type *); \
|
||||||
|
attr struct type *name##_RB_INSERT(struct name *, struct type *); \
|
||||||
|
attr struct type *name##_RB_FIND(struct name *, struct type *); \
|
||||||
|
attr struct type *name##_RB_NFIND(struct name *, struct type *); \
|
||||||
|
attr struct type *name##_RB_NEXT(struct type *); \
|
||||||
|
attr struct type *name##_RB_PREV(struct type *); \
|
||||||
|
attr struct type *name##_RB_MINMAX(struct name *, int); \
|
||||||
|
\
|
||||||
|
|
||||||
|
/* Main rb operation.
|
||||||
|
* Moves node close to the key of elm to top
|
||||||
|
*/
|
||||||
|
#define RB_GENERATE(name, type, field, cmp) \
|
||||||
|
RB_GENERATE_INTERNAL(name, type, field, cmp,)
|
||||||
|
#define RB_GENERATE_STATIC(name, type, field, cmp) \
|
||||||
|
RB_GENERATE_INTERNAL(name, type, field, cmp, UV__UNUSED static)
|
||||||
|
#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \
|
||||||
|
attr void \
|
||||||
|
name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \
|
||||||
|
{ \
|
||||||
|
struct type *parent, *gparent, *tmp; \
|
||||||
|
while ((parent = RB_PARENT(elm, field)) != NULL && \
|
||||||
|
RB_COLOR(parent, field) == RB_RED) { \
|
||||||
|
gparent = RB_PARENT(parent, field); \
|
||||||
|
if (parent == RB_LEFT(gparent, field)) { \
|
||||||
|
tmp = RB_RIGHT(gparent, field); \
|
||||||
|
if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
|
||||||
|
RB_COLOR(tmp, field) = RB_BLACK; \
|
||||||
|
RB_SET_BLACKRED(parent, gparent, field); \
|
||||||
|
elm = gparent; \
|
||||||
|
continue; \
|
||||||
|
} \
|
||||||
|
if (RB_RIGHT(parent, field) == elm) { \
|
||||||
|
RB_ROTATE_LEFT(head, parent, tmp, field); \
|
||||||
|
tmp = parent; \
|
||||||
|
parent = elm; \
|
||||||
|
elm = tmp; \
|
||||||
|
} \
|
||||||
|
RB_SET_BLACKRED(parent, gparent, field); \
|
||||||
|
RB_ROTATE_RIGHT(head, gparent, tmp, field); \
|
||||||
|
} else { \
|
||||||
|
tmp = RB_LEFT(gparent, field); \
|
||||||
|
if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
|
||||||
|
RB_COLOR(tmp, field) = RB_BLACK; \
|
||||||
|
RB_SET_BLACKRED(parent, gparent, field); \
|
||||||
|
elm = gparent; \
|
||||||
|
continue; \
|
||||||
|
} \
|
||||||
|
if (RB_LEFT(parent, field) == elm) { \
|
||||||
|
RB_ROTATE_RIGHT(head, parent, tmp, field); \
|
||||||
|
tmp = parent; \
|
||||||
|
parent = elm; \
|
||||||
|
elm = tmp; \
|
||||||
|
} \
|
||||||
|
RB_SET_BLACKRED(parent, gparent, field); \
|
||||||
|
RB_ROTATE_LEFT(head, gparent, tmp, field); \
|
||||||
|
} \
|
||||||
|
} \
|
||||||
|
RB_COLOR(head->rbh_root, field) = RB_BLACK; \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
attr void \
|
||||||
|
name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, \
|
||||||
|
struct type *elm) \
|
||||||
|
{ \
|
||||||
|
struct type *tmp; \
|
||||||
|
while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \
|
||||||
|
elm != RB_ROOT(head)) { \
|
||||||
|
if (RB_LEFT(parent, field) == elm) { \
|
||||||
|
tmp = RB_RIGHT(parent, field); \
|
||||||
|
if (RB_COLOR(tmp, field) == RB_RED) { \
|
||||||
|
RB_SET_BLACKRED(tmp, parent, field); \
|
||||||
|
RB_ROTATE_LEFT(head, parent, tmp, field); \
|
||||||
|
tmp = RB_RIGHT(parent, field); \
|
||||||
|
} \
|
||||||
|
if ((RB_LEFT(tmp, field) == NULL || \
|
||||||
|
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) && \
|
||||||
|
(RB_RIGHT(tmp, field) == NULL || \
|
||||||
|
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) { \
|
||||||
|
RB_COLOR(tmp, field) = RB_RED; \
|
||||||
|
elm = parent; \
|
||||||
|
parent = RB_PARENT(elm, field); \
|
||||||
|
} else { \
|
||||||
|
if (RB_RIGHT(tmp, field) == NULL || \
|
||||||
|
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) { \
|
||||||
|
struct type *oleft; \
|
||||||
|
if ((oleft = RB_LEFT(tmp, field)) \
|
||||||
|
!= NULL) \
|
||||||
|
RB_COLOR(oleft, field) = RB_BLACK; \
|
||||||
|
RB_COLOR(tmp, field) = RB_RED; \
|
||||||
|
RB_ROTATE_RIGHT(head, tmp, oleft, field); \
|
||||||
|
tmp = RB_RIGHT(parent, field); \
|
||||||
|
} \
|
||||||
|
RB_COLOR(tmp, field) = RB_COLOR(parent, field); \
|
||||||
|
RB_COLOR(parent, field) = RB_BLACK; \
|
||||||
|
if (RB_RIGHT(tmp, field)) \
|
||||||
|
RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK; \
|
||||||
|
RB_ROTATE_LEFT(head, parent, tmp, field); \
|
||||||
|
elm = RB_ROOT(head); \
|
||||||
|
break; \
|
||||||
|
} \
|
||||||
|
} else { \
|
||||||
|
tmp = RB_LEFT(parent, field); \
|
||||||
|
if (RB_COLOR(tmp, field) == RB_RED) { \
|
||||||
|
RB_SET_BLACKRED(tmp, parent, field); \
|
||||||
|
RB_ROTATE_RIGHT(head, parent, tmp, field); \
|
||||||
|
tmp = RB_LEFT(parent, field); \
|
||||||
|
} \
|
||||||
|
if ((RB_LEFT(tmp, field) == NULL || \
|
||||||
|
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) && \
|
||||||
|
(RB_RIGHT(tmp, field) == NULL || \
|
||||||
|
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) { \
|
||||||
|
RB_COLOR(tmp, field) = RB_RED; \
|
||||||
|
elm = parent; \
|
||||||
|
parent = RB_PARENT(elm, field); \
|
||||||
|
} else { \
|
||||||
|
if (RB_LEFT(tmp, field) == NULL || \
|
||||||
|
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) { \
|
||||||
|
struct type *oright; \
|
||||||
|
if ((oright = RB_RIGHT(tmp, field)) \
|
||||||
|
!= NULL) \
|
||||||
|
RB_COLOR(oright, field) = RB_BLACK; \
|
||||||
|
RB_COLOR(tmp, field) = RB_RED; \
|
||||||
|
RB_ROTATE_LEFT(head, tmp, oright, field); \
|
||||||
|
tmp = RB_LEFT(parent, field); \
|
||||||
|
} \
|
||||||
|
RB_COLOR(tmp, field) = RB_COLOR(parent, field); \
|
||||||
|
RB_COLOR(parent, field) = RB_BLACK; \
|
||||||
|
if (RB_LEFT(tmp, field)) \
|
||||||
|
RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK; \
|
||||||
|
RB_ROTATE_RIGHT(head, parent, tmp, field); \
|
||||||
|
elm = RB_ROOT(head); \
|
||||||
|
break; \
|
||||||
|
} \
|
||||||
|
} \
|
||||||
|
} \
|
||||||
|
if (elm) \
|
||||||
|
RB_COLOR(elm, field) = RB_BLACK; \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
attr struct type * \
|
||||||
|
name##_RB_REMOVE(struct name *head, struct type *elm) \
|
||||||
|
{ \
|
||||||
|
struct type *child, *parent, *old = elm; \
|
||||||
|
int color; \
|
||||||
|
if (RB_LEFT(elm, field) == NULL) \
|
||||||
|
child = RB_RIGHT(elm, field); \
|
||||||
|
else if (RB_RIGHT(elm, field) == NULL) \
|
||||||
|
child = RB_LEFT(elm, field); \
|
||||||
|
else { \
|
||||||
|
struct type *left; \
|
||||||
|
elm = RB_RIGHT(elm, field); \
|
||||||
|
while ((left = RB_LEFT(elm, field)) != NULL) \
|
||||||
|
elm = left; \
|
||||||
|
child = RB_RIGHT(elm, field); \
|
||||||
|
parent = RB_PARENT(elm, field); \
|
||||||
|
color = RB_COLOR(elm, field); \
|
||||||
|
if (child) \
|
||||||
|
RB_PARENT(child, field) = parent; \
|
||||||
|
if (parent) { \
|
||||||
|
if (RB_LEFT(parent, field) == elm) \
|
||||||
|
RB_LEFT(parent, field) = child; \
|
||||||
|
else \
|
||||||
|
RB_RIGHT(parent, field) = child; \
|
||||||
|
RB_AUGMENT(parent); \
|
||||||
|
} else \
|
||||||
|
RB_ROOT(head) = child; \
|
||||||
|
if (RB_PARENT(elm, field) == old) \
|
||||||
|
parent = elm; \
|
||||||
|
(elm)->field = (old)->field; \
|
||||||
|
if (RB_PARENT(old, field)) { \
|
||||||
|
if (RB_LEFT(RB_PARENT(old, field), field) == old) \
|
||||||
|
RB_LEFT(RB_PARENT(old, field), field) = elm; \
|
||||||
|
else \
|
||||||
|
RB_RIGHT(RB_PARENT(old, field), field) = elm; \
|
||||||
|
RB_AUGMENT(RB_PARENT(old, field)); \
|
||||||
|
} else \
|
||||||
|
RB_ROOT(head) = elm; \
|
||||||
|
RB_PARENT(RB_LEFT(old, field), field) = elm; \
|
||||||
|
if (RB_RIGHT(old, field)) \
|
||||||
|
RB_PARENT(RB_RIGHT(old, field), field) = elm; \
|
||||||
|
if (parent) { \
|
||||||
|
left = parent; \
|
||||||
|
do { \
|
||||||
|
RB_AUGMENT(left); \
|
||||||
|
} while ((left = RB_PARENT(left, field)) != NULL); \
|
||||||
|
} \
|
||||||
|
goto color; \
|
||||||
|
} \
|
||||||
|
parent = RB_PARENT(elm, field); \
|
||||||
|
color = RB_COLOR(elm, field); \
|
||||||
|
if (child) \
|
||||||
|
RB_PARENT(child, field) = parent; \
|
||||||
|
if (parent) { \
|
||||||
|
if (RB_LEFT(parent, field) == elm) \
|
||||||
|
RB_LEFT(parent, field) = child; \
|
||||||
|
else \
|
||||||
|
RB_RIGHT(parent, field) = child; \
|
||||||
|
RB_AUGMENT(parent); \
|
||||||
|
} else \
|
||||||
|
RB_ROOT(head) = child; \
|
||||||
|
color: \
|
||||||
|
if (color == RB_BLACK) \
|
||||||
|
name##_RB_REMOVE_COLOR(head, parent, child); \
|
||||||
|
return (old); \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
/* Inserts a node into the RB tree */ \
|
||||||
|
attr struct type * \
|
||||||
|
name##_RB_INSERT(struct name *head, struct type *elm) \
|
||||||
|
{ \
|
||||||
|
struct type *tmp; \
|
||||||
|
struct type *parent = NULL; \
|
||||||
|
int comp = 0; \
|
||||||
|
tmp = RB_ROOT(head); \
|
||||||
|
while (tmp) { \
|
||||||
|
parent = tmp; \
|
||||||
|
comp = (cmp)(elm, parent); \
|
||||||
|
if (comp < 0) \
|
||||||
|
tmp = RB_LEFT(tmp, field); \
|
||||||
|
else if (comp > 0) \
|
||||||
|
tmp = RB_RIGHT(tmp, field); \
|
||||||
|
else \
|
||||||
|
return (tmp); \
|
||||||
|
} \
|
||||||
|
RB_SET(elm, parent, field); \
|
||||||
|
if (parent != NULL) { \
|
||||||
|
if (comp < 0) \
|
||||||
|
RB_LEFT(parent, field) = elm; \
|
||||||
|
else \
|
||||||
|
RB_RIGHT(parent, field) = elm; \
|
||||||
|
RB_AUGMENT(parent); \
|
||||||
|
} else \
|
||||||
|
RB_ROOT(head) = elm; \
|
||||||
|
name##_RB_INSERT_COLOR(head, elm); \
|
||||||
|
return (NULL); \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
/* Finds the node with the same key as elm */ \
|
||||||
|
attr struct type * \
|
||||||
|
name##_RB_FIND(struct name *head, struct type *elm) \
|
||||||
|
{ \
|
||||||
|
struct type *tmp = RB_ROOT(head); \
|
||||||
|
int comp; \
|
||||||
|
while (tmp) { \
|
||||||
|
comp = cmp(elm, tmp); \
|
||||||
|
if (comp < 0) \
|
||||||
|
tmp = RB_LEFT(tmp, field); \
|
||||||
|
else if (comp > 0) \
|
||||||
|
tmp = RB_RIGHT(tmp, field); \
|
||||||
|
else \
|
||||||
|
return (tmp); \
|
||||||
|
} \
|
||||||
|
return (NULL); \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
/* Finds the first node greater than or equal to the search key */ \
|
||||||
|
attr struct type * \
|
||||||
|
name##_RB_NFIND(struct name *head, struct type *elm) \
|
||||||
|
{ \
|
||||||
|
struct type *tmp = RB_ROOT(head); \
|
||||||
|
struct type *res = NULL; \
|
||||||
|
int comp; \
|
||||||
|
while (tmp) { \
|
||||||
|
comp = cmp(elm, tmp); \
|
||||||
|
if (comp < 0) { \
|
||||||
|
res = tmp; \
|
||||||
|
tmp = RB_LEFT(tmp, field); \
|
||||||
|
} \
|
||||||
|
else if (comp > 0) \
|
||||||
|
tmp = RB_RIGHT(tmp, field); \
|
||||||
|
else \
|
||||||
|
return (tmp); \
|
||||||
|
} \
|
||||||
|
return (res); \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
/* ARGSUSED */ \
|
||||||
|
attr struct type * \
|
||||||
|
name##_RB_NEXT(struct type *elm) \
|
||||||
|
{ \
|
||||||
|
if (RB_RIGHT(elm, field)) { \
|
||||||
|
elm = RB_RIGHT(elm, field); \
|
||||||
|
while (RB_LEFT(elm, field)) \
|
||||||
|
elm = RB_LEFT(elm, field); \
|
||||||
|
} else { \
|
||||||
|
if (RB_PARENT(elm, field) && \
|
||||||
|
(elm == RB_LEFT(RB_PARENT(elm, field), field))) \
|
||||||
|
elm = RB_PARENT(elm, field); \
|
||||||
|
else { \
|
||||||
|
while (RB_PARENT(elm, field) && \
|
||||||
|
(elm == RB_RIGHT(RB_PARENT(elm, field), field))) \
|
||||||
|
elm = RB_PARENT(elm, field); \
|
||||||
|
elm = RB_PARENT(elm, field); \
|
||||||
|
} \
|
||||||
|
} \
|
||||||
|
return (elm); \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
/* ARGSUSED */ \
|
||||||
|
attr struct type * \
|
||||||
|
name##_RB_PREV(struct type *elm) \
|
||||||
|
{ \
|
||||||
|
if (RB_LEFT(elm, field)) { \
|
||||||
|
elm = RB_LEFT(elm, field); \
|
||||||
|
while (RB_RIGHT(elm, field)) \
|
||||||
|
elm = RB_RIGHT(elm, field); \
|
||||||
|
} else { \
|
||||||
|
if (RB_PARENT(elm, field) && \
|
||||||
|
(elm == RB_RIGHT(RB_PARENT(elm, field), field))) \
|
||||||
|
elm = RB_PARENT(elm, field); \
|
||||||
|
else { \
|
||||||
|
while (RB_PARENT(elm, field) && \
|
||||||
|
(elm == RB_LEFT(RB_PARENT(elm, field), field))) \
|
||||||
|
elm = RB_PARENT(elm, field); \
|
||||||
|
elm = RB_PARENT(elm, field); \
|
||||||
|
} \
|
||||||
|
} \
|
||||||
|
return (elm); \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
attr struct type * \
|
||||||
|
name##_RB_MINMAX(struct name *head, int val) \
|
||||||
|
{ \
|
||||||
|
struct type *tmp = RB_ROOT(head); \
|
||||||
|
struct type *parent = NULL; \
|
||||||
|
while (tmp) { \
|
||||||
|
parent = tmp; \
|
||||||
|
if (val < 0) \
|
||||||
|
tmp = RB_LEFT(tmp, field); \
|
||||||
|
else \
|
||||||
|
tmp = RB_RIGHT(tmp, field); \
|
||||||
|
} \
|
||||||
|
return (parent); \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define RB_NEGINF -1
|
||||||
|
#define RB_INF 1
|
||||||
|
|
||||||
|
#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y)
|
||||||
|
#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y)
|
||||||
|
#define RB_FIND(name, x, y) name##_RB_FIND(x, y)
|
||||||
|
#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y)
|
||||||
|
#define RB_NEXT(name, x) name##_RB_NEXT(x)
|
||||||
|
#define RB_PREV(name, x) name##_RB_PREV(x)
|
||||||
|
#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF)
|
||||||
|
#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF)
|
||||||
|
|
||||||
|
#define RB_FOREACH(x, name, head) \
|
||||||
|
for ((x) = RB_MIN(name, head); \
|
||||||
|
(x) != NULL; \
|
||||||
|
(x) = name##_RB_NEXT(x))
|
||||||
|
|
||||||
|
#define RB_FOREACH_FROM(x, name, y) \
|
||||||
|
for ((x) = (y); \
|
||||||
|
((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \
|
||||||
|
(x) = (y))
|
||||||
|
|
||||||
|
#define RB_FOREACH_SAFE(x, name, head, y) \
|
||||||
|
for ((x) = RB_MIN(name, head); \
|
||||||
|
((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \
|
||||||
|
(x) = (y))
|
||||||
|
|
||||||
|
#define RB_FOREACH_REVERSE(x, name, head) \
|
||||||
|
for ((x) = RB_MAX(name, head); \
|
||||||
|
(x) != NULL; \
|
||||||
|
(x) = name##_RB_PREV(x))
|
||||||
|
|
||||||
|
#define RB_FOREACH_REVERSE_FROM(x, name, y) \
|
||||||
|
for ((x) = (y); \
|
||||||
|
((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \
|
||||||
|
(x) = (y))
|
||||||
|
|
||||||
|
#define RB_FOREACH_REVERSE_SAFE(x, name, head, y) \
|
||||||
|
for ((x) = RB_MAX(name, head); \
|
||||||
|
((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \
|
||||||
|
(x) = (y))
|
||||||
|
|
||||||
|
#endif /* UV_TREE_H_ */
|
||||||
@@ -0,0 +1,509 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_UNIX_H
|
||||||
|
#define UV_UNIX_H
|
||||||
|
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <dirent.h>
|
||||||
|
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <netinet/in.h>
|
||||||
|
#include <netinet/tcp.h>
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <netdb.h> /* MAXHOSTNAMELEN on Solaris */
|
||||||
|
|
||||||
|
#include <termios.h>
|
||||||
|
#include <pwd.h>
|
||||||
|
|
||||||
|
#if !defined(__MVS__)
|
||||||
|
#include <semaphore.h>
|
||||||
|
#include <sys/param.h> /* MAXHOSTNAMELEN on Linux and the BSDs */
|
||||||
|
#endif
|
||||||
|
#include <pthread.h>
|
||||||
|
#include <signal.h>
|
||||||
|
|
||||||
|
#include "uv/threadpool.h"
|
||||||
|
|
||||||
|
#if defined(__linux__)
|
||||||
|
# include "uv/linux.h"
|
||||||
|
#elif defined (__MVS__)
|
||||||
|
# include "uv/os390.h"
|
||||||
|
#elif defined(__PASE__) /* __PASE__ and _AIX are both defined on IBM i */
|
||||||
|
# include "uv/posix.h" /* IBM i needs uv/posix.h, not uv/aix.h */
|
||||||
|
#elif defined(_AIX)
|
||||||
|
# include "uv/aix.h"
|
||||||
|
#elif defined(__sun)
|
||||||
|
# include "uv/sunos.h"
|
||||||
|
#elif defined(__APPLE__)
|
||||||
|
# include "uv/darwin.h"
|
||||||
|
#elif defined(__DragonFly__) || \
|
||||||
|
defined(__FreeBSD__) || \
|
||||||
|
defined(__OpenBSD__) || \
|
||||||
|
defined(__NetBSD__)
|
||||||
|
# include "uv/bsd.h"
|
||||||
|
#elif defined(__CYGWIN__) || \
|
||||||
|
defined(__MSYS__) || \
|
||||||
|
defined(__HAIKU__) || \
|
||||||
|
defined(__QNX__) || \
|
||||||
|
defined(__GNU__)
|
||||||
|
# include "uv/posix.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef NI_MAXHOST
|
||||||
|
# define NI_MAXHOST 1025
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef NI_MAXSERV
|
||||||
|
# define NI_MAXSERV 32
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef UV_IO_PRIVATE_PLATFORM_FIELDS
|
||||||
|
# define UV_IO_PRIVATE_PLATFORM_FIELDS /* empty */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
struct uv__io_s;
|
||||||
|
struct uv_loop_s;
|
||||||
|
|
||||||
|
typedef struct uv__io_s uv__io_t;
|
||||||
|
|
||||||
|
struct uv__io_s {
|
||||||
|
uintptr_t bits;
|
||||||
|
struct uv__queue pending_queue;
|
||||||
|
struct uv__queue watcher_queue;
|
||||||
|
unsigned int pevents; /* Pending event mask i.e. mask at next tick. */
|
||||||
|
unsigned int events; /* Current event mask. */
|
||||||
|
int fd;
|
||||||
|
UV_IO_PRIVATE_PLATFORM_FIELDS
|
||||||
|
};
|
||||||
|
|
||||||
|
#ifndef UV_PLATFORM_SEM_T
|
||||||
|
# define UV_PLATFORM_SEM_T sem_t
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef UV_PLATFORM_LOOP_FIELDS
|
||||||
|
# define UV_PLATFORM_LOOP_FIELDS /* empty */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef UV_PLATFORM_FS_EVENT_FIELDS
|
||||||
|
# define UV_PLATFORM_FS_EVENT_FIELDS /* empty */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef UV_STREAM_PRIVATE_PLATFORM_FIELDS
|
||||||
|
# define UV_STREAM_PRIVATE_PLATFORM_FIELDS /* empty */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Note: May be cast to struct iovec. See writev(2). */
|
||||||
|
typedef struct uv_buf_t {
|
||||||
|
char* base;
|
||||||
|
size_t len;
|
||||||
|
} uv_buf_t;
|
||||||
|
|
||||||
|
typedef int uv_file;
|
||||||
|
typedef int uv_os_sock_t;
|
||||||
|
typedef int uv_os_fd_t;
|
||||||
|
typedef pid_t uv_pid_t;
|
||||||
|
|
||||||
|
#define UV_ONCE_INIT PTHREAD_ONCE_INIT
|
||||||
|
|
||||||
|
typedef pthread_once_t uv_once_t;
|
||||||
|
typedef pthread_t uv_thread_t;
|
||||||
|
typedef pthread_mutex_t uv_mutex_t;
|
||||||
|
typedef pthread_rwlock_t uv_rwlock_t;
|
||||||
|
typedef UV_PLATFORM_SEM_T uv_sem_t;
|
||||||
|
typedef pthread_cond_t uv_cond_t;
|
||||||
|
typedef pthread_key_t uv_key_t;
|
||||||
|
|
||||||
|
/* Note: guard clauses should match uv_barrier_init's in src/unix/thread.c. */
|
||||||
|
#if defined(_AIX) || \
|
||||||
|
defined(__OpenBSD__) || \
|
||||||
|
!defined(PTHREAD_BARRIER_SERIAL_THREAD)
|
||||||
|
/* TODO(bnoordhuis) Merge into uv_barrier_t in v2. */
|
||||||
|
struct _uv_barrier {
|
||||||
|
uv_mutex_t mutex;
|
||||||
|
uv_cond_t cond;
|
||||||
|
unsigned threshold;
|
||||||
|
unsigned in;
|
||||||
|
unsigned out;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
struct _uv_barrier* b;
|
||||||
|
# if defined(PTHREAD_BARRIER_SERIAL_THREAD)
|
||||||
|
/* TODO(bnoordhuis) Remove padding in v2. */
|
||||||
|
char pad[sizeof(pthread_barrier_t) - sizeof(struct _uv_barrier*)];
|
||||||
|
# endif
|
||||||
|
} uv_barrier_t;
|
||||||
|
#else
|
||||||
|
typedef pthread_barrier_t uv_barrier_t;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Platform-specific definitions for uv_spawn support. */
|
||||||
|
typedef gid_t uv_gid_t;
|
||||||
|
typedef uid_t uv_uid_t;
|
||||||
|
|
||||||
|
typedef struct dirent uv__dirent_t;
|
||||||
|
|
||||||
|
#define UV_DIR_PRIVATE_FIELDS \
|
||||||
|
DIR* dir;
|
||||||
|
|
||||||
|
#if defined(DT_UNKNOWN)
|
||||||
|
# define HAVE_DIRENT_TYPES
|
||||||
|
# if defined(DT_REG)
|
||||||
|
# define UV__DT_FILE DT_REG
|
||||||
|
# else
|
||||||
|
# define UV__DT_FILE -1
|
||||||
|
# endif
|
||||||
|
# if defined(DT_DIR)
|
||||||
|
# define UV__DT_DIR DT_DIR
|
||||||
|
# else
|
||||||
|
# define UV__DT_DIR -2
|
||||||
|
# endif
|
||||||
|
# if defined(DT_LNK)
|
||||||
|
# define UV__DT_LINK DT_LNK
|
||||||
|
# else
|
||||||
|
# define UV__DT_LINK -3
|
||||||
|
# endif
|
||||||
|
# if defined(DT_FIFO)
|
||||||
|
# define UV__DT_FIFO DT_FIFO
|
||||||
|
# else
|
||||||
|
# define UV__DT_FIFO -4
|
||||||
|
# endif
|
||||||
|
# if defined(DT_SOCK)
|
||||||
|
# define UV__DT_SOCKET DT_SOCK
|
||||||
|
# else
|
||||||
|
# define UV__DT_SOCKET -5
|
||||||
|
# endif
|
||||||
|
# if defined(DT_CHR)
|
||||||
|
# define UV__DT_CHAR DT_CHR
|
||||||
|
# else
|
||||||
|
# define UV__DT_CHAR -6
|
||||||
|
# endif
|
||||||
|
# if defined(DT_BLK)
|
||||||
|
# define UV__DT_BLOCK DT_BLK
|
||||||
|
# else
|
||||||
|
# define UV__DT_BLOCK -7
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Platform-specific definitions for uv_dlopen support. */
|
||||||
|
#define UV_DYNAMIC /* empty */
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
void* handle;
|
||||||
|
char* errmsg;
|
||||||
|
} uv_lib_t;
|
||||||
|
|
||||||
|
#define UV_LOOP_PRIVATE_FIELDS \
|
||||||
|
unsigned long flags; \
|
||||||
|
int backend_fd; \
|
||||||
|
struct uv__queue pending_queue; \
|
||||||
|
struct uv__queue watcher_queue; \
|
||||||
|
uv__io_t** watchers; \
|
||||||
|
unsigned int nwatchers; \
|
||||||
|
unsigned int nfds; \
|
||||||
|
struct uv__queue wq; \
|
||||||
|
uv_mutex_t wq_mutex; \
|
||||||
|
uv_async_t wq_async; \
|
||||||
|
uv_rwlock_t cloexec_lock; \
|
||||||
|
uv_handle_t* closing_handles; \
|
||||||
|
struct uv__queue process_handles; \
|
||||||
|
struct uv__queue prepare_handles; \
|
||||||
|
struct uv__queue check_handles; \
|
||||||
|
struct uv__queue idle_handles; \
|
||||||
|
struct uv__queue async_handles; \
|
||||||
|
void (*async_unused)(void); /* TODO(bnoordhuis) Remove in libuv v2. */ \
|
||||||
|
uv__io_t async_io_watcher; \
|
||||||
|
int async_wfd; \
|
||||||
|
struct { \
|
||||||
|
void* min; \
|
||||||
|
unsigned int nelts; \
|
||||||
|
} timer_heap; \
|
||||||
|
uint64_t timer_counter; \
|
||||||
|
uint64_t time; \
|
||||||
|
int signal_pipefd[2]; \
|
||||||
|
uv__io_t signal_io_watcher; \
|
||||||
|
uv_signal_t child_watcher; \
|
||||||
|
int emfile_fd; \
|
||||||
|
UV_PLATFORM_LOOP_FIELDS \
|
||||||
|
|
||||||
|
#define UV_REQ_TYPE_PRIVATE /* empty */
|
||||||
|
|
||||||
|
#define UV_REQ_PRIVATE_FIELDS /* empty */
|
||||||
|
|
||||||
|
#define UV_PRIVATE_REQ_TYPES /* empty */
|
||||||
|
|
||||||
|
#define UV_WRITE_PRIVATE_FIELDS \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
unsigned int write_index; \
|
||||||
|
uv_buf_t* bufs; \
|
||||||
|
unsigned int nbufs; \
|
||||||
|
int error; \
|
||||||
|
uv_buf_t bufsml[4]; \
|
||||||
|
|
||||||
|
#define UV_CONNECT_PRIVATE_FIELDS \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
|
||||||
|
#define UV_SHUTDOWN_PRIVATE_FIELDS /* empty */
|
||||||
|
|
||||||
|
#define UV_UDP_SEND_PRIVATE_FIELDS \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
union { \
|
||||||
|
struct sockaddr addr; \
|
||||||
|
struct sockaddr_storage storage; \
|
||||||
|
} u; \
|
||||||
|
unsigned int nbufs; \
|
||||||
|
uv_buf_t* bufs; \
|
||||||
|
ssize_t status; \
|
||||||
|
uv_udp_send_cb send_cb; \
|
||||||
|
uv_buf_t bufsml[4]; \
|
||||||
|
|
||||||
|
#define UV_HANDLE_PRIVATE_FIELDS \
|
||||||
|
uv_handle_t* next_closing; \
|
||||||
|
unsigned int flags; \
|
||||||
|
|
||||||
|
#define UV_STREAM_PRIVATE_FIELDS \
|
||||||
|
uv_connect_t *connect_req; \
|
||||||
|
uv_shutdown_t *shutdown_req; \
|
||||||
|
uv__io_t io_watcher; \
|
||||||
|
struct uv__queue write_queue; \
|
||||||
|
struct uv__queue write_completed_queue; \
|
||||||
|
uv_connection_cb connection_cb; \
|
||||||
|
int delayed_error; \
|
||||||
|
int accepted_fd; \
|
||||||
|
void* queued_fds; \
|
||||||
|
UV_STREAM_PRIVATE_PLATFORM_FIELDS \
|
||||||
|
|
||||||
|
#define UV_TCP_PRIVATE_FIELDS /* empty */
|
||||||
|
|
||||||
|
#define UV_UDP_PRIVATE_FIELDS \
|
||||||
|
uv_alloc_cb alloc_cb; \
|
||||||
|
uv_udp_recv_cb recv_cb; \
|
||||||
|
uv__io_t io_watcher; \
|
||||||
|
struct uv__queue write_queue; \
|
||||||
|
struct uv__queue write_completed_queue; \
|
||||||
|
|
||||||
|
#define UV_PIPE_PRIVATE_FIELDS \
|
||||||
|
const char* pipe_fname; /* NULL or strdup'ed */
|
||||||
|
|
||||||
|
#define UV_POLL_PRIVATE_FIELDS \
|
||||||
|
uv__io_t io_watcher;
|
||||||
|
|
||||||
|
#define UV_PREPARE_PRIVATE_FIELDS \
|
||||||
|
uv_prepare_cb prepare_cb; \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
|
||||||
|
#define UV_CHECK_PRIVATE_FIELDS \
|
||||||
|
uv_check_cb check_cb; \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
|
||||||
|
#define UV_IDLE_PRIVATE_FIELDS \
|
||||||
|
uv_idle_cb idle_cb; \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
|
||||||
|
#define UV_ASYNC_PRIVATE_FIELDS \
|
||||||
|
uv_async_cb async_cb; \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
int pending; \
|
||||||
|
|
||||||
|
#define UV_TIMER_PRIVATE_FIELDS \
|
||||||
|
uv_timer_cb timer_cb; \
|
||||||
|
union { \
|
||||||
|
void* heap[3]; \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
} node; \
|
||||||
|
uint64_t timeout; \
|
||||||
|
uint64_t repeat; \
|
||||||
|
uint64_t start_id;
|
||||||
|
|
||||||
|
#define UV_GETADDRINFO_PRIVATE_FIELDS \
|
||||||
|
struct uv__work work_req; \
|
||||||
|
uv_getaddrinfo_cb cb; \
|
||||||
|
struct addrinfo* hints; \
|
||||||
|
char* hostname; \
|
||||||
|
char* service; \
|
||||||
|
struct addrinfo* addrinfo; \
|
||||||
|
int retcode;
|
||||||
|
|
||||||
|
#define UV_GETNAMEINFO_PRIVATE_FIELDS \
|
||||||
|
struct uv__work work_req; \
|
||||||
|
uv_getnameinfo_cb getnameinfo_cb; \
|
||||||
|
struct sockaddr_storage storage; \
|
||||||
|
int flags; \
|
||||||
|
char host[NI_MAXHOST]; \
|
||||||
|
char service[NI_MAXSERV]; \
|
||||||
|
int retcode;
|
||||||
|
|
||||||
|
#define UV_PROCESS_PRIVATE_FIELDS \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
int status; \
|
||||||
|
|
||||||
|
#define UV_FS_PRIVATE_FIELDS \
|
||||||
|
const char *new_path; \
|
||||||
|
uv_file file; \
|
||||||
|
int flags; \
|
||||||
|
mode_t mode; \
|
||||||
|
unsigned int nbufs; \
|
||||||
|
uv_buf_t* bufs; \
|
||||||
|
off_t off; \
|
||||||
|
uv_uid_t uid; \
|
||||||
|
uv_gid_t gid; \
|
||||||
|
double atime; \
|
||||||
|
double mtime; \
|
||||||
|
struct uv__work work_req; \
|
||||||
|
uv_buf_t bufsml[4]; \
|
||||||
|
|
||||||
|
#define UV_WORK_PRIVATE_FIELDS \
|
||||||
|
struct uv__work work_req;
|
||||||
|
|
||||||
|
#define UV_TTY_PRIVATE_FIELDS \
|
||||||
|
struct termios orig_termios; \
|
||||||
|
int mode;
|
||||||
|
|
||||||
|
#define UV_SIGNAL_PRIVATE_FIELDS \
|
||||||
|
/* RB_ENTRY(uv_signal_s) tree_entry; */ \
|
||||||
|
struct { \
|
||||||
|
struct uv_signal_s* rbe_left; \
|
||||||
|
struct uv_signal_s* rbe_right; \
|
||||||
|
struct uv_signal_s* rbe_parent; \
|
||||||
|
int rbe_color; \
|
||||||
|
} tree_entry; \
|
||||||
|
/* Use two counters here so we don have to fiddle with atomics. */ \
|
||||||
|
unsigned int caught_signals; \
|
||||||
|
unsigned int dispatched_signals;
|
||||||
|
|
||||||
|
#define UV_FS_EVENT_PRIVATE_FIELDS \
|
||||||
|
uv_fs_event_cb cb; \
|
||||||
|
UV_PLATFORM_FS_EVENT_FIELDS \
|
||||||
|
|
||||||
|
/* fs open() flags supported on this platform: */
|
||||||
|
#if defined(O_APPEND)
|
||||||
|
# define UV_FS_O_APPEND O_APPEND
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_APPEND 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_CREAT)
|
||||||
|
# define UV_FS_O_CREAT O_CREAT
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_CREAT 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(__linux__) && defined(__arm__)
|
||||||
|
# define UV_FS_O_DIRECT 0x10000
|
||||||
|
#elif defined(__linux__) && defined(__m68k__)
|
||||||
|
# define UV_FS_O_DIRECT 0x10000
|
||||||
|
#elif defined(__linux__) && defined(__mips__)
|
||||||
|
# define UV_FS_O_DIRECT 0x08000
|
||||||
|
#elif defined(__linux__) && defined(__powerpc__)
|
||||||
|
# define UV_FS_O_DIRECT 0x20000
|
||||||
|
#elif defined(__linux__) && defined(__s390x__)
|
||||||
|
# define UV_FS_O_DIRECT 0x04000
|
||||||
|
#elif defined(__linux__) && defined(__x86_64__)
|
||||||
|
# define UV_FS_O_DIRECT 0x04000
|
||||||
|
#elif defined(__linux__) && defined(__loongarch__)
|
||||||
|
# define UV_FS_O_DIRECT 0x04000
|
||||||
|
#elif defined(O_DIRECT)
|
||||||
|
# define UV_FS_O_DIRECT O_DIRECT
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_DIRECT 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(O_DIRECTORY)
|
||||||
|
# define UV_FS_O_DIRECTORY O_DIRECTORY
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_DIRECTORY 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_DSYNC)
|
||||||
|
# define UV_FS_O_DSYNC O_DSYNC
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_DSYNC 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_EXCL)
|
||||||
|
# define UV_FS_O_EXCL O_EXCL
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_EXCL 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_EXLOCK)
|
||||||
|
# define UV_FS_O_EXLOCK O_EXLOCK
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_EXLOCK 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_NOATIME)
|
||||||
|
# define UV_FS_O_NOATIME O_NOATIME
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_NOATIME 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_NOCTTY)
|
||||||
|
# define UV_FS_O_NOCTTY O_NOCTTY
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_NOCTTY 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_NOFOLLOW)
|
||||||
|
# define UV_FS_O_NOFOLLOW O_NOFOLLOW
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_NOFOLLOW 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_NONBLOCK)
|
||||||
|
# define UV_FS_O_NONBLOCK O_NONBLOCK
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_NONBLOCK 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_RDONLY)
|
||||||
|
# define UV_FS_O_RDONLY O_RDONLY
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_RDONLY 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_RDWR)
|
||||||
|
# define UV_FS_O_RDWR O_RDWR
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_RDWR 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_SYMLINK)
|
||||||
|
# define UV_FS_O_SYMLINK O_SYMLINK
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_SYMLINK 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_SYNC)
|
||||||
|
# define UV_FS_O_SYNC O_SYNC
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_SYNC 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_TRUNC)
|
||||||
|
# define UV_FS_O_TRUNC O_TRUNC
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_TRUNC 0
|
||||||
|
#endif
|
||||||
|
#if defined(O_WRONLY)
|
||||||
|
# define UV_FS_O_WRONLY O_WRONLY
|
||||||
|
#else
|
||||||
|
# define UV_FS_O_WRONLY 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* fs open() flags supported on other platforms: */
|
||||||
|
#define UV_FS_O_FILEMAP 0
|
||||||
|
#define UV_FS_O_RANDOM 0
|
||||||
|
#define UV_FS_O_SHORT_LIVED 0
|
||||||
|
#define UV_FS_O_SEQUENTIAL 0
|
||||||
|
#define UV_FS_O_TEMPORARY 0
|
||||||
|
|
||||||
|
#endif /* UV_UNIX_H */
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef UV_VERSION_H
|
||||||
|
#define UV_VERSION_H
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Versions with the same major number are ABI stable. API is allowed to
|
||||||
|
* evolve between minor releases, but only in a backwards compatible way.
|
||||||
|
* Make sure you update the -soname directives in configure.ac
|
||||||
|
* whenever you bump UV_VERSION_MAJOR or UV_VERSION_MINOR (but
|
||||||
|
* not UV_VERSION_PATCH.)
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define UV_VERSION_MAJOR 1
|
||||||
|
#define UV_VERSION_MINOR 51
|
||||||
|
#define UV_VERSION_PATCH 1
|
||||||
|
#define UV_VERSION_IS_RELEASE 0
|
||||||
|
#define UV_VERSION_SUFFIX "dev"
|
||||||
|
|
||||||
|
#define UV_VERSION_HEX ((UV_VERSION_MAJOR << 16) | \
|
||||||
|
(UV_VERSION_MINOR << 8) | \
|
||||||
|
(UV_VERSION_PATCH))
|
||||||
|
|
||||||
|
#endif /* UV_VERSION_H */
|
||||||
@@ -0,0 +1,698 @@
|
|||||||
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to
|
||||||
|
* deal in the Software without restriction, including without limitation the
|
||||||
|
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||||
|
* sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
* IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef _WIN32_WINNT
|
||||||
|
# define _WIN32_WINNT 0x0A00
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
|
||||||
|
typedef intptr_t ssize_t;
|
||||||
|
# define SSIZE_MAX INTPTR_MAX
|
||||||
|
# define _SSIZE_T_
|
||||||
|
# define _SSIZE_T_DEFINED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <winsock2.h>
|
||||||
|
|
||||||
|
#ifndef LOCALE_INVARIANT
|
||||||
|
# define LOCALE_INVARIANT 0x007f
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <mswsock.h>
|
||||||
|
/* Disable the typedef in mstcpip.h of MinGW. */
|
||||||
|
#define _TCP_INITIAL_RTO_PARAMETERS _TCP_INITIAL_RTO_PARAMETERS__AVOID
|
||||||
|
#define TCP_INITIAL_RTO_PARAMETERS TCP_INITIAL_RTO_PARAMETERS__AVOID
|
||||||
|
#define PTCP_INITIAL_RTO_PARAMETERS PTCP_INITIAL_RTO_PARAMETERS__AVOID
|
||||||
|
#include <ws2tcpip.h>
|
||||||
|
#undef _TCP_INITIAL_RTO_PARAMETERS
|
||||||
|
#undef TCP_INITIAL_RTO_PARAMETERS
|
||||||
|
#undef PTCP_INITIAL_RTO_PARAMETERS
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
#include <process.h>
|
||||||
|
#include <signal.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "uv/tree.h"
|
||||||
|
#include "uv/threadpool.h"
|
||||||
|
|
||||||
|
#define MAX_PIPENAME_LEN 256
|
||||||
|
|
||||||
|
#ifndef S_IFLNK
|
||||||
|
# define S_IFLNK 0xA000
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Define missing in Windows Kit Include\{VERSION}\ucrt\sys\stat.h */
|
||||||
|
#if defined(_CRT_INTERNAL_NONSTDC_NAMES) && _CRT_INTERNAL_NONSTDC_NAMES && !defined(S_IFIFO)
|
||||||
|
# define S_IFIFO _S_IFIFO
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Additional signals supported by uv_signal and or uv_kill. The CRT defines
|
||||||
|
* the following signals already:
|
||||||
|
*
|
||||||
|
* #define SIGINT 2
|
||||||
|
* #define SIGILL 4
|
||||||
|
* #define SIGABRT_COMPAT 6
|
||||||
|
* #define SIGFPE 8
|
||||||
|
* #define SIGSEGV 11
|
||||||
|
* #define SIGTERM 15
|
||||||
|
* #define SIGBREAK 21
|
||||||
|
* #define SIGABRT 22
|
||||||
|
*
|
||||||
|
* The additional signals have values that are common on other Unix
|
||||||
|
* variants (Linux and Darwin)
|
||||||
|
*/
|
||||||
|
#define SIGHUP 1
|
||||||
|
#define SIGQUIT 3
|
||||||
|
#define SIGKILL 9
|
||||||
|
#define SIGWINCH 28
|
||||||
|
|
||||||
|
/* Redefine NSIG to take SIGWINCH into consideration */
|
||||||
|
#if defined(NSIG) && NSIG <= SIGWINCH
|
||||||
|
# undef NSIG
|
||||||
|
#endif
|
||||||
|
#ifndef NSIG
|
||||||
|
# define NSIG SIGWINCH + 1
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* The CRT defines SIGABRT_COMPAT as 6, which equals SIGABRT on many unix-like
|
||||||
|
* platforms. However MinGW doesn't define it, so we do. */
|
||||||
|
#ifndef SIGABRT_COMPAT
|
||||||
|
# define SIGABRT_COMPAT 6
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Guids and typedefs for winsock extension functions
|
||||||
|
* Mingw32 doesn't have these :-(
|
||||||
|
*/
|
||||||
|
#ifndef WSAID_ACCEPTEX
|
||||||
|
# define WSAID_ACCEPTEX \
|
||||||
|
{0xb5367df1, 0xcbac, 0x11cf, \
|
||||||
|
{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
|
||||||
|
|
||||||
|
# define WSAID_CONNECTEX \
|
||||||
|
{0x25a207b9, 0xddf3, 0x4660, \
|
||||||
|
{0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}}
|
||||||
|
|
||||||
|
# define WSAID_GETACCEPTEXSOCKADDRS \
|
||||||
|
{0xb5367df2, 0xcbac, 0x11cf, \
|
||||||
|
{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
|
||||||
|
|
||||||
|
# define WSAID_DISCONNECTEX \
|
||||||
|
{0x7fda2e11, 0x8630, 0x436f, \
|
||||||
|
{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
|
||||||
|
|
||||||
|
# define WSAID_TRANSMITFILE \
|
||||||
|
{0xb5367df0, 0xcbac, 0x11cf, \
|
||||||
|
{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
|
||||||
|
|
||||||
|
typedef BOOL (PASCAL *LPFN_ACCEPTEX)
|
||||||
|
(SOCKET sListenSocket,
|
||||||
|
SOCKET sAcceptSocket,
|
||||||
|
PVOID lpOutputBuffer,
|
||||||
|
DWORD dwReceiveDataLength,
|
||||||
|
DWORD dwLocalAddressLength,
|
||||||
|
DWORD dwRemoteAddressLength,
|
||||||
|
LPDWORD lpdwBytesReceived,
|
||||||
|
LPOVERLAPPED lpOverlapped);
|
||||||
|
|
||||||
|
typedef BOOL (PASCAL *LPFN_CONNECTEX)
|
||||||
|
(SOCKET s,
|
||||||
|
const struct sockaddr* name,
|
||||||
|
int namelen,
|
||||||
|
PVOID lpSendBuffer,
|
||||||
|
DWORD dwSendDataLength,
|
||||||
|
LPDWORD lpdwBytesSent,
|
||||||
|
LPOVERLAPPED lpOverlapped);
|
||||||
|
|
||||||
|
typedef void (PASCAL *LPFN_GETACCEPTEXSOCKADDRS)
|
||||||
|
(PVOID lpOutputBuffer,
|
||||||
|
DWORD dwReceiveDataLength,
|
||||||
|
DWORD dwLocalAddressLength,
|
||||||
|
DWORD dwRemoteAddressLength,
|
||||||
|
LPSOCKADDR* LocalSockaddr,
|
||||||
|
LPINT LocalSockaddrLength,
|
||||||
|
LPSOCKADDR* RemoteSockaddr,
|
||||||
|
LPINT RemoteSockaddrLength);
|
||||||
|
|
||||||
|
typedef BOOL (PASCAL *LPFN_DISCONNECTEX)
|
||||||
|
(SOCKET hSocket,
|
||||||
|
LPOVERLAPPED lpOverlapped,
|
||||||
|
DWORD dwFlags,
|
||||||
|
DWORD reserved);
|
||||||
|
|
||||||
|
typedef BOOL (PASCAL *LPFN_TRANSMITFILE)
|
||||||
|
(SOCKET hSocket,
|
||||||
|
HANDLE hFile,
|
||||||
|
DWORD nNumberOfBytesToWrite,
|
||||||
|
DWORD nNumberOfBytesPerSend,
|
||||||
|
LPOVERLAPPED lpOverlapped,
|
||||||
|
LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers,
|
||||||
|
DWORD dwFlags);
|
||||||
|
|
||||||
|
typedef PVOID RTL_SRWLOCK;
|
||||||
|
typedef RTL_SRWLOCK SRWLOCK, *PSRWLOCK;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
typedef int (WSAAPI* LPFN_WSARECV)
|
||||||
|
(SOCKET socket,
|
||||||
|
LPWSABUF buffers,
|
||||||
|
DWORD buffer_count,
|
||||||
|
LPDWORD bytes,
|
||||||
|
LPDWORD flags,
|
||||||
|
LPWSAOVERLAPPED overlapped,
|
||||||
|
LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine);
|
||||||
|
|
||||||
|
typedef int (WSAAPI* LPFN_WSARECVFROM)
|
||||||
|
(SOCKET socket,
|
||||||
|
LPWSABUF buffers,
|
||||||
|
DWORD buffer_count,
|
||||||
|
LPDWORD bytes,
|
||||||
|
LPDWORD flags,
|
||||||
|
struct sockaddr* addr,
|
||||||
|
LPINT addr_len,
|
||||||
|
LPWSAOVERLAPPED overlapped,
|
||||||
|
LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine);
|
||||||
|
|
||||||
|
#ifndef _NTDEF_
|
||||||
|
typedef LONG NTSTATUS;
|
||||||
|
typedef NTSTATUS *PNTSTATUS;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef RTL_CONDITION_VARIABLE_INIT
|
||||||
|
typedef PVOID CONDITION_VARIABLE, *PCONDITION_VARIABLE;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
typedef struct _AFD_POLL_HANDLE_INFO {
|
||||||
|
HANDLE Handle;
|
||||||
|
ULONG Events;
|
||||||
|
NTSTATUS Status;
|
||||||
|
} AFD_POLL_HANDLE_INFO, *PAFD_POLL_HANDLE_INFO;
|
||||||
|
|
||||||
|
typedef struct _AFD_POLL_INFO {
|
||||||
|
LARGE_INTEGER Timeout;
|
||||||
|
ULONG NumberOfHandles;
|
||||||
|
ULONG Exclusive;
|
||||||
|
AFD_POLL_HANDLE_INFO Handles[1];
|
||||||
|
} AFD_POLL_INFO, *PAFD_POLL_INFO;
|
||||||
|
|
||||||
|
#define UV_MSAFD_PROVIDER_COUNT 4
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* It should be possible to cast uv_buf_t[] to WSABUF[]
|
||||||
|
* see http://msdn.microsoft.com/en-us/library/ms741542(v=vs.85).aspx
|
||||||
|
*/
|
||||||
|
typedef struct uv_buf_t {
|
||||||
|
ULONG len;
|
||||||
|
char* base;
|
||||||
|
} uv_buf_t;
|
||||||
|
|
||||||
|
typedef int uv_file;
|
||||||
|
typedef SOCKET uv_os_sock_t;
|
||||||
|
typedef HANDLE uv_os_fd_t;
|
||||||
|
typedef int uv_pid_t;
|
||||||
|
|
||||||
|
typedef HANDLE uv_thread_t;
|
||||||
|
|
||||||
|
typedef HANDLE uv_sem_t;
|
||||||
|
|
||||||
|
typedef CRITICAL_SECTION uv_mutex_t;
|
||||||
|
|
||||||
|
/* This condition variable implementation is based on the SetEvent solution
|
||||||
|
* (section 3.2) at http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
|
||||||
|
* We could not use the SignalObjectAndWait solution (section 3.4) because
|
||||||
|
* it want the 2nd argument (type uv_mutex_t) of uv_cond_wait() and
|
||||||
|
* uv_cond_timedwait() to be HANDLEs, but we use CRITICAL_SECTIONs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
typedef union {
|
||||||
|
CONDITION_VARIABLE cond_var;
|
||||||
|
struct {
|
||||||
|
unsigned int waiters_count;
|
||||||
|
CRITICAL_SECTION waiters_count_lock;
|
||||||
|
HANDLE signal_event;
|
||||||
|
HANDLE broadcast_event;
|
||||||
|
} unused_; /* TODO: retained for ABI compatibility; remove me in v2.x. */
|
||||||
|
} uv_cond_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
SRWLOCK read_write_lock_;
|
||||||
|
/* TODO: retained for ABI compatibility; remove me in v2.x */
|
||||||
|
#ifdef _WIN64
|
||||||
|
unsigned char padding_[72];
|
||||||
|
#else
|
||||||
|
unsigned char padding_[44];
|
||||||
|
#endif
|
||||||
|
} uv_rwlock_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
unsigned threshold;
|
||||||
|
unsigned in;
|
||||||
|
uv_mutex_t mutex;
|
||||||
|
/* TODO: in v2 make this a uv_cond_t, without unused_ */
|
||||||
|
CONDITION_VARIABLE cond;
|
||||||
|
unsigned out;
|
||||||
|
} uv_barrier_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
DWORD tls_index;
|
||||||
|
} uv_key_t;
|
||||||
|
|
||||||
|
#define UV_ONCE_INIT { 0, { NULL } }
|
||||||
|
|
||||||
|
typedef struct uv_once_s {
|
||||||
|
unsigned char unused;
|
||||||
|
INIT_ONCE init_once;
|
||||||
|
} uv_once_t;
|
||||||
|
|
||||||
|
/* Platform-specific definitions for uv_spawn support. */
|
||||||
|
typedef unsigned char uv_uid_t;
|
||||||
|
typedef unsigned char uv_gid_t;
|
||||||
|
|
||||||
|
typedef struct uv__dirent_s {
|
||||||
|
int d_type;
|
||||||
|
char d_name[1];
|
||||||
|
} uv__dirent_t;
|
||||||
|
|
||||||
|
#define UV_DIR_PRIVATE_FIELDS \
|
||||||
|
HANDLE dir_handle; \
|
||||||
|
WIN32_FIND_DATAW find_data; \
|
||||||
|
BOOL need_find_call;
|
||||||
|
|
||||||
|
#define HAVE_DIRENT_TYPES
|
||||||
|
#define UV__DT_DIR UV_DIRENT_DIR
|
||||||
|
#define UV__DT_FILE UV_DIRENT_FILE
|
||||||
|
#define UV__DT_LINK UV_DIRENT_LINK
|
||||||
|
#define UV__DT_FIFO UV_DIRENT_FIFO
|
||||||
|
#define UV__DT_SOCKET UV_DIRENT_SOCKET
|
||||||
|
#define UV__DT_CHAR UV_DIRENT_CHAR
|
||||||
|
#define UV__DT_BLOCK UV_DIRENT_BLOCK
|
||||||
|
|
||||||
|
/* Platform-specific definitions for uv_dlopen support. */
|
||||||
|
#define UV_DYNAMIC FAR WINAPI
|
||||||
|
typedef struct {
|
||||||
|
HMODULE handle;
|
||||||
|
char* errmsg;
|
||||||
|
} uv_lib_t;
|
||||||
|
|
||||||
|
#define UV_LOOP_PRIVATE_FIELDS \
|
||||||
|
/* The loop's I/O completion port */ \
|
||||||
|
HANDLE iocp; \
|
||||||
|
/* The current time according to the event loop. in msecs. */ \
|
||||||
|
uint64_t time; \
|
||||||
|
/* Tail of a single-linked circular queue of pending reqs. If the queue */ \
|
||||||
|
/* is empty, tail_ is NULL. If there is only one item, */ \
|
||||||
|
/* tail_->next_req == tail_ */ \
|
||||||
|
uv_req_t* pending_reqs_tail; \
|
||||||
|
/* Head of a single-linked list of closed handles */ \
|
||||||
|
uv_handle_t* endgame_handles; \
|
||||||
|
/* TODO(bnoordhuis) Stop heap-allocating |timer_heap| in libuv v2.x. */ \
|
||||||
|
void* timer_heap; \
|
||||||
|
/* Lists of active loop (prepare / check / idle) watchers */ \
|
||||||
|
uv_prepare_t* prepare_handles; \
|
||||||
|
uv_check_t* check_handles; \
|
||||||
|
uv_idle_t* idle_handles; \
|
||||||
|
/* This pointer will refer to the prepare/check/idle handle whose */ \
|
||||||
|
/* callback is scheduled to be called next. This is needed to allow */ \
|
||||||
|
/* safe removal from one of the lists above while that list being */ \
|
||||||
|
/* iterated over. */ \
|
||||||
|
uv_prepare_t* next_prepare_handle; \
|
||||||
|
uv_check_t* next_check_handle; \
|
||||||
|
uv_idle_t* next_idle_handle; \
|
||||||
|
/* This handle holds the peer sockets for the fast variant of uv_poll_t */ \
|
||||||
|
SOCKET poll_peer_sockets[UV_MSAFD_PROVIDER_COUNT]; \
|
||||||
|
/* No longer used. */ \
|
||||||
|
unsigned int active_tcp_streams; \
|
||||||
|
/* No longer used. */ \
|
||||||
|
unsigned int active_udp_streams; \
|
||||||
|
/* Counter to started timer */ \
|
||||||
|
uint64_t timer_counter; \
|
||||||
|
/* Threadpool */ \
|
||||||
|
struct uv__queue wq; \
|
||||||
|
uv_mutex_t wq_mutex; \
|
||||||
|
uv_async_t wq_async;
|
||||||
|
|
||||||
|
#define UV_REQ_TYPE_PRIVATE \
|
||||||
|
/* TODO: remove the req suffix */ \
|
||||||
|
UV_ACCEPT, \
|
||||||
|
UV_FS_EVENT_REQ, \
|
||||||
|
UV_POLL_REQ, \
|
||||||
|
UV_PROCESS_EXIT, \
|
||||||
|
UV_READ, \
|
||||||
|
UV_UDP_RECV, \
|
||||||
|
UV_WAKEUP, \
|
||||||
|
UV_SIGNAL_REQ,
|
||||||
|
|
||||||
|
#define UV_REQ_PRIVATE_FIELDS \
|
||||||
|
union { \
|
||||||
|
/* Used by I/O operations */ \
|
||||||
|
struct { \
|
||||||
|
OVERLAPPED overlapped; \
|
||||||
|
size_t queued_bytes; \
|
||||||
|
} io; \
|
||||||
|
/* in v2, we can move these to the UV_CONNECT_PRIVATE_FIELDS */ \
|
||||||
|
struct { \
|
||||||
|
ULONG_PTR result; /* overlapped.Internal is reused to hold the result */\
|
||||||
|
HANDLE pipeHandle; \
|
||||||
|
DWORD duplex_flags; \
|
||||||
|
WCHAR* name; \
|
||||||
|
} connect; \
|
||||||
|
} u; \
|
||||||
|
struct uv_req_s* next_req;
|
||||||
|
|
||||||
|
#define UV_WRITE_PRIVATE_FIELDS \
|
||||||
|
int coalesced; \
|
||||||
|
uv_buf_t write_buffer; \
|
||||||
|
HANDLE event_handle; \
|
||||||
|
HANDLE wait_handle;
|
||||||
|
|
||||||
|
#define UV_CONNECT_PRIVATE_FIELDS \
|
||||||
|
/* empty */
|
||||||
|
|
||||||
|
#define UV_SHUTDOWN_PRIVATE_FIELDS \
|
||||||
|
/* empty */
|
||||||
|
|
||||||
|
#define UV_UDP_SEND_PRIVATE_FIELDS \
|
||||||
|
/* empty */
|
||||||
|
|
||||||
|
#define UV_PRIVATE_REQ_TYPES \
|
||||||
|
typedef struct uv_pipe_accept_s { \
|
||||||
|
UV_REQ_FIELDS \
|
||||||
|
HANDLE pipeHandle; \
|
||||||
|
struct uv_pipe_accept_s* next_pending; \
|
||||||
|
} uv_pipe_accept_t; \
|
||||||
|
\
|
||||||
|
typedef struct uv_tcp_accept_s { \
|
||||||
|
UV_REQ_FIELDS \
|
||||||
|
SOCKET accept_socket; \
|
||||||
|
char accept_buffer[sizeof(struct sockaddr_storage) * 2 + 32]; \
|
||||||
|
HANDLE event_handle; \
|
||||||
|
HANDLE wait_handle; \
|
||||||
|
struct uv_tcp_accept_s* next_pending; \
|
||||||
|
} uv_tcp_accept_t; \
|
||||||
|
\
|
||||||
|
typedef struct uv_read_s { \
|
||||||
|
UV_REQ_FIELDS \
|
||||||
|
HANDLE event_handle; \
|
||||||
|
HANDLE wait_handle; \
|
||||||
|
} uv_read_t;
|
||||||
|
|
||||||
|
#define uv_stream_connection_fields \
|
||||||
|
unsigned int write_reqs_pending; \
|
||||||
|
uv_shutdown_t* shutdown_req;
|
||||||
|
|
||||||
|
#define uv_stream_server_fields \
|
||||||
|
uv_connection_cb connection_cb;
|
||||||
|
|
||||||
|
#define UV_STREAM_PRIVATE_FIELDS \
|
||||||
|
unsigned int reqs_pending; \
|
||||||
|
int activecnt; \
|
||||||
|
uv_read_t read_req; \
|
||||||
|
union { \
|
||||||
|
struct { uv_stream_connection_fields } conn; \
|
||||||
|
struct { uv_stream_server_fields } serv; \
|
||||||
|
} stream;
|
||||||
|
|
||||||
|
#define uv_tcp_server_fields \
|
||||||
|
uv_tcp_accept_t* accept_reqs; \
|
||||||
|
unsigned int processed_accepts; \
|
||||||
|
uv_tcp_accept_t* pending_accepts; \
|
||||||
|
LPFN_ACCEPTEX func_acceptex;
|
||||||
|
|
||||||
|
#define uv_tcp_connection_fields \
|
||||||
|
uv_buf_t read_buffer; \
|
||||||
|
LPFN_CONNECTEX func_connectex;
|
||||||
|
|
||||||
|
#define UV_TCP_PRIVATE_FIELDS \
|
||||||
|
SOCKET socket; \
|
||||||
|
int delayed_error; \
|
||||||
|
union { \
|
||||||
|
struct { uv_tcp_server_fields } serv; \
|
||||||
|
struct { uv_tcp_connection_fields } conn; \
|
||||||
|
} tcp;
|
||||||
|
|
||||||
|
#define UV_UDP_PRIVATE_FIELDS \
|
||||||
|
SOCKET socket; \
|
||||||
|
unsigned int reqs_pending; \
|
||||||
|
int activecnt; \
|
||||||
|
uv_req_t recv_req; \
|
||||||
|
uv_buf_t recv_buffer; \
|
||||||
|
struct sockaddr_storage recv_from; \
|
||||||
|
int recv_from_len; \
|
||||||
|
uv_udp_recv_cb recv_cb; \
|
||||||
|
uv_alloc_cb alloc_cb; \
|
||||||
|
LPFN_WSARECV func_wsarecv; \
|
||||||
|
LPFN_WSARECVFROM func_wsarecvfrom;
|
||||||
|
|
||||||
|
#define uv_pipe_server_fields \
|
||||||
|
int pending_instances; \
|
||||||
|
uv_pipe_accept_t* accept_reqs; \
|
||||||
|
uv_pipe_accept_t* pending_accepts;
|
||||||
|
|
||||||
|
#define uv_pipe_connection_fields \
|
||||||
|
uv_timer_t* eof_timer; \
|
||||||
|
uv_write_t dummy; /* TODO: retained for ABI compat; remove this in v2.x. */ \
|
||||||
|
DWORD ipc_remote_pid; \
|
||||||
|
union { \
|
||||||
|
uint32_t payload_remaining; \
|
||||||
|
uint64_t dummy; /* TODO: retained for ABI compat; remove this in v2.x. */ \
|
||||||
|
} ipc_data_frame; \
|
||||||
|
struct uv__queue ipc_xfer_queue; \
|
||||||
|
int ipc_xfer_queue_length; \
|
||||||
|
uv_write_t* non_overlapped_writes_tail; \
|
||||||
|
CRITICAL_SECTION readfile_thread_lock; \
|
||||||
|
volatile HANDLE readfile_thread_handle;
|
||||||
|
|
||||||
|
#define UV_PIPE_PRIVATE_FIELDS \
|
||||||
|
HANDLE handle; \
|
||||||
|
WCHAR* name; \
|
||||||
|
union { \
|
||||||
|
struct { uv_pipe_server_fields } serv; \
|
||||||
|
struct { uv_pipe_connection_fields } conn; \
|
||||||
|
} pipe;
|
||||||
|
|
||||||
|
/* TODO: put the parser states in a union - TTY handles are always half-duplex
|
||||||
|
* so read-state can safely overlap write-state. */
|
||||||
|
#define UV_TTY_PRIVATE_FIELDS \
|
||||||
|
HANDLE handle; \
|
||||||
|
union { \
|
||||||
|
struct { \
|
||||||
|
/* Used for readable TTY handles */ \
|
||||||
|
union { \
|
||||||
|
/* TODO: remove me in v2.x. */ \
|
||||||
|
HANDLE unused_; \
|
||||||
|
int mode; \
|
||||||
|
} mode; \
|
||||||
|
uv_buf_t read_line_buffer; \
|
||||||
|
HANDLE read_raw_wait; \
|
||||||
|
/* Fields used for translating win keystrokes into vt100 characters */ \
|
||||||
|
char last_key[8]; \
|
||||||
|
unsigned char last_key_offset; \
|
||||||
|
unsigned char last_key_len; \
|
||||||
|
WCHAR last_utf16_high_surrogate; \
|
||||||
|
INPUT_RECORD last_input_record; \
|
||||||
|
} rd; \
|
||||||
|
struct { \
|
||||||
|
/* Used for writable TTY handles */ \
|
||||||
|
/* utf8-to-utf16 conversion state */ \
|
||||||
|
unsigned int utf8_codepoint; \
|
||||||
|
unsigned char utf8_bytes_left; \
|
||||||
|
/* eol conversion state */ \
|
||||||
|
unsigned char previous_eol; \
|
||||||
|
/* ansi parser state */ \
|
||||||
|
unsigned short ansi_parser_state; \
|
||||||
|
unsigned char ansi_csi_argc; \
|
||||||
|
unsigned short ansi_csi_argv[4]; \
|
||||||
|
COORD saved_position; \
|
||||||
|
WORD saved_attributes; \
|
||||||
|
} wr; \
|
||||||
|
} tty;
|
||||||
|
|
||||||
|
#define UV_POLL_PRIVATE_FIELDS \
|
||||||
|
SOCKET socket; \
|
||||||
|
/* Used in fast mode */ \
|
||||||
|
SOCKET peer_socket; \
|
||||||
|
AFD_POLL_INFO afd_poll_info_1; \
|
||||||
|
AFD_POLL_INFO afd_poll_info_2; \
|
||||||
|
/* Used in fast and slow mode. */ \
|
||||||
|
uv_req_t poll_req_1; \
|
||||||
|
uv_req_t poll_req_2; \
|
||||||
|
unsigned char submitted_events_1; \
|
||||||
|
unsigned char submitted_events_2; \
|
||||||
|
unsigned char mask_events_1; \
|
||||||
|
unsigned char mask_events_2; \
|
||||||
|
unsigned char events;
|
||||||
|
|
||||||
|
#define UV_TIMER_PRIVATE_FIELDS \
|
||||||
|
union { \
|
||||||
|
void* heap[3]; \
|
||||||
|
struct uv__queue queue; \
|
||||||
|
} node; \
|
||||||
|
int unused; \
|
||||||
|
uint64_t timeout; \
|
||||||
|
uint64_t repeat; \
|
||||||
|
uint64_t start_id; \
|
||||||
|
uv_timer_cb timer_cb;
|
||||||
|
|
||||||
|
#define UV_ASYNC_PRIVATE_FIELDS \
|
||||||
|
struct uv_req_s async_req; \
|
||||||
|
uv_async_cb async_cb; \
|
||||||
|
/* char to avoid alignment issues */ \
|
||||||
|
char volatile async_sent;
|
||||||
|
|
||||||
|
#define UV_PREPARE_PRIVATE_FIELDS \
|
||||||
|
uv_prepare_t* prepare_prev; \
|
||||||
|
uv_prepare_t* prepare_next; \
|
||||||
|
uv_prepare_cb prepare_cb;
|
||||||
|
|
||||||
|
#define UV_CHECK_PRIVATE_FIELDS \
|
||||||
|
uv_check_t* check_prev; \
|
||||||
|
uv_check_t* check_next; \
|
||||||
|
uv_check_cb check_cb;
|
||||||
|
|
||||||
|
#define UV_IDLE_PRIVATE_FIELDS \
|
||||||
|
uv_idle_t* idle_prev; \
|
||||||
|
uv_idle_t* idle_next; \
|
||||||
|
uv_idle_cb idle_cb;
|
||||||
|
|
||||||
|
#define UV_HANDLE_PRIVATE_FIELDS \
|
||||||
|
uv_handle_t* endgame_next; \
|
||||||
|
unsigned int flags;
|
||||||
|
|
||||||
|
#define UV_GETADDRINFO_PRIVATE_FIELDS \
|
||||||
|
struct uv__work work_req; \
|
||||||
|
uv_getaddrinfo_cb getaddrinfo_cb; \
|
||||||
|
void* alloc; \
|
||||||
|
WCHAR* node; \
|
||||||
|
WCHAR* service; \
|
||||||
|
/* The addrinfoW field is used to store a pointer to the hints, and */ \
|
||||||
|
/* later on to store the result of GetAddrInfoW. The final result will */ \
|
||||||
|
/* be converted to struct addrinfo* and stored in the addrinfo field. */ \
|
||||||
|
struct addrinfoW* addrinfow; \
|
||||||
|
struct addrinfo* addrinfo; \
|
||||||
|
int retcode;
|
||||||
|
|
||||||
|
#define UV_GETNAMEINFO_PRIVATE_FIELDS \
|
||||||
|
struct uv__work work_req; \
|
||||||
|
uv_getnameinfo_cb getnameinfo_cb; \
|
||||||
|
struct sockaddr_storage storage; \
|
||||||
|
int flags; \
|
||||||
|
char host[NI_MAXHOST]; \
|
||||||
|
char service[NI_MAXSERV]; \
|
||||||
|
int retcode;
|
||||||
|
|
||||||
|
#define UV_PROCESS_PRIVATE_FIELDS \
|
||||||
|
struct uv_process_exit_s { \
|
||||||
|
UV_REQ_FIELDS \
|
||||||
|
} exit_req; \
|
||||||
|
void* unused; /* TODO: retained for ABI compat; remove this in v2.x. */ \
|
||||||
|
int exit_signal; \
|
||||||
|
HANDLE wait_handle; \
|
||||||
|
HANDLE process_handle; \
|
||||||
|
volatile char exit_cb_pending;
|
||||||
|
|
||||||
|
#define UV_FS_PRIVATE_FIELDS \
|
||||||
|
struct uv__work work_req; \
|
||||||
|
int flags; \
|
||||||
|
DWORD sys_errno_; \
|
||||||
|
union { \
|
||||||
|
/* TODO: remove me in 0.9. */ \
|
||||||
|
WCHAR* pathw; \
|
||||||
|
int fd; \
|
||||||
|
} file; \
|
||||||
|
union { \
|
||||||
|
struct { \
|
||||||
|
int mode; \
|
||||||
|
WCHAR* new_pathw; \
|
||||||
|
int file_flags; \
|
||||||
|
int fd_out; \
|
||||||
|
unsigned int nbufs; \
|
||||||
|
uv_buf_t* bufs; \
|
||||||
|
int64_t offset; \
|
||||||
|
uv_buf_t bufsml[4]; \
|
||||||
|
} info; \
|
||||||
|
struct { \
|
||||||
|
double atime; \
|
||||||
|
double mtime; \
|
||||||
|
} time; \
|
||||||
|
} fs;
|
||||||
|
|
||||||
|
#define UV_WORK_PRIVATE_FIELDS \
|
||||||
|
struct uv__work work_req;
|
||||||
|
|
||||||
|
#define UV_FS_EVENT_PRIVATE_FIELDS \
|
||||||
|
struct uv_fs_event_req_s { \
|
||||||
|
UV_REQ_FIELDS \
|
||||||
|
} req; \
|
||||||
|
HANDLE dir_handle; \
|
||||||
|
int req_pending; \
|
||||||
|
uv_fs_event_cb cb; \
|
||||||
|
WCHAR* filew; \
|
||||||
|
WCHAR* short_filew; \
|
||||||
|
WCHAR* dirw; \
|
||||||
|
char* buffer;
|
||||||
|
|
||||||
|
#define UV_SIGNAL_PRIVATE_FIELDS \
|
||||||
|
RB_ENTRY(uv_signal_s) tree_entry; \
|
||||||
|
struct uv_req_s signal_req; \
|
||||||
|
unsigned long pending_signum;
|
||||||
|
|
||||||
|
#ifndef F_OK
|
||||||
|
#define F_OK 0
|
||||||
|
#endif
|
||||||
|
#ifndef R_OK
|
||||||
|
#define R_OK 4
|
||||||
|
#endif
|
||||||
|
#ifndef W_OK
|
||||||
|
#define W_OK 2
|
||||||
|
#endif
|
||||||
|
#ifndef X_OK
|
||||||
|
#define X_OK 1
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* fs open() flags supported on this platform: */
|
||||||
|
#define UV_FS_O_APPEND _O_APPEND
|
||||||
|
#define UV_FS_O_CREAT _O_CREAT
|
||||||
|
#define UV_FS_O_EXCL _O_EXCL
|
||||||
|
#define UV_FS_O_FILEMAP 0x20000000
|
||||||
|
#define UV_FS_O_RANDOM _O_RANDOM
|
||||||
|
#define UV_FS_O_RDONLY _O_RDONLY
|
||||||
|
#define UV_FS_O_RDWR _O_RDWR
|
||||||
|
#define UV_FS_O_SEQUENTIAL _O_SEQUENTIAL
|
||||||
|
#define UV_FS_O_SHORT_LIVED _O_SHORT_LIVED
|
||||||
|
#define UV_FS_O_TEMPORARY _O_TEMPORARY
|
||||||
|
#define UV_FS_O_TRUNC _O_TRUNC
|
||||||
|
#define UV_FS_O_WRONLY _O_WRONLY
|
||||||
|
|
||||||
|
/* fs open() flags supported on other platforms (or mapped on this platform): */
|
||||||
|
#define UV_FS_O_DIRECT 0x02000000 /* FILE_FLAG_NO_BUFFERING */
|
||||||
|
#define UV_FS_O_DIRECTORY 0
|
||||||
|
#define UV_FS_O_DSYNC 0x04000000 /* FILE_FLAG_WRITE_THROUGH */
|
||||||
|
#define UV_FS_O_EXLOCK 0x10000000 /* EXCLUSIVE SHARING MODE */
|
||||||
|
#define UV_FS_O_NOATIME 0
|
||||||
|
#define UV_FS_O_NOCTTY 0
|
||||||
|
#define UV_FS_O_NOFOLLOW 0
|
||||||
|
#define UV_FS_O_NONBLOCK 0
|
||||||
|
#define UV_FS_O_SYMLINK 0
|
||||||
|
#define UV_FS_O_SYNC 0x08000000 /* FILE_FLAG_WRITE_THROUGH */
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
module usockets
|
||||||
|
|
||||||
|
// 条件编译:根据操作系统选择正确的路径和库
|
||||||
|
// @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"
|
||||||
|
|
||||||
|
pub type Loop = &C.us_loop_t
|
||||||
|
pub type SocketContext = &C.us_socket_context_t
|
||||||
|
pub type Socket = &C.us_socket_t
|
||||||
|
pub type ListenSocket = &C.us_listen_socket_t
|
||||||
|
|
||||||
|
struct C.us_loop_t {}
|
||||||
|
struct C.us_socket_context_t {}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
fn C.us_create_loop(hint voidptr, wakeup_cb voidptr, pre_cb voidptr, post_cb voidptr, ext_size u32) Loop
|
||||||
|
fn C.us_loop_free(loop Loop)
|
||||||
|
fn C.us_loop_run(loop Loop)
|
||||||
|
|
||||||
|
fn C.us_create_socket_context(ssl int, loop Loop, ext_size int, options C.us_socket_context_options_t) SocketContext
|
||||||
|
fn C.us_socket_context_free(ssl int, context SocketContext)
|
||||||
|
fn C.us_socket_context_on_open(ssl int, context SocketContext, on_open voidptr)
|
||||||
|
fn C.us_socket_context_on_close(ssl int, context SocketContext, on_close voidptr)
|
||||||
|
fn C.us_socket_context_on_data(ssl int, context SocketContext, on_data voidptr)
|
||||||
|
fn C.us_socket_context_on_writable(ssl int, context SocketContext, on_writable voidptr)
|
||||||
|
fn C.us_socket_context_on_timeout(ssl int, context SocketContext, on_timeout voidptr)
|
||||||
|
fn C.us_socket_context_on_end(ssl int, context SocketContext, on_end voidptr)
|
||||||
|
fn C.us_socket_context_listen(ssl int, context SocketContext, host voidptr, port int, options int, socket_ext_size int) ListenSocket
|
||||||
|
|
||||||
|
fn C.us_socket_write(ssl int, socket Socket, data &char, length int, msg_more int) int
|
||||||
|
fn C.us_socket_shutdown(ssl int, socket Socket)
|
||||||
|
fn C.us_socket_close(ssl int, socket Socket, code int, reason voidptr) Socket
|
||||||
|
|
||||||
|
fn C.us_listen_socket_close(ssl int, ls ListenSocket)
|
||||||
|
|
||||||
|
fn empty_wakeup(loop Loop) {}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn (ctx SocketContext) free() { C.us_socket_context_free(0, ctx) }
|
||||||
|
pub fn (ctx SocketContext) on_open(h voidptr) { C.us_socket_context_on_open(0, ctx, h) }
|
||||||
|
pub fn (ctx SocketContext) on_close(h voidptr) { C.us_socket_context_on_close(0, ctx, h) }
|
||||||
|
pub fn (ctx SocketContext) on_data(h voidptr) { C.us_socket_context_on_data(0, ctx, h) }
|
||||||
|
pub fn (ctx SocketContext) on_writable(h voidptr) { C.us_socket_context_on_writable(0, ctx, h) }
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn (s Socket) write_bytes(data string) int { return C.us_socket_write(0, s, data.str, data.len, 0) }
|
||||||
|
pub fn (s Socket) shutdown() { C.us_socket_shutdown(0, s) }
|
||||||
|
pub fn (s Socket) close() Socket { return C.us_socket_close(0, s, 0, unsafe { nil }) }
|
||||||
|
|
||||||
|
pub fn (ls ListenSocket) close() { C.us_listen_socket_close(0, ls) }
|
||||||
|
pub fn (ls ListenSocket) is_valid() bool { return ls != unsafe { nil } }
|
||||||
@@ -0,0 +1,463 @@
|
|||||||
|
// uSockets Server Backend for V-Hono
|
||||||
|
//
|
||||||
|
// 这个文件提供 V-Hono 的 uSockets 高性能服务器后端
|
||||||
|
//
|
||||||
|
// 安装步骤:
|
||||||
|
// 1. 将 usockets 目录复制到 V-Hono 项目目录
|
||||||
|
// 2. 将此文件复制到 V-Hono 项目根目录
|
||||||
|
// 3. 修改 usockets/usockets.v 中的路径为绝对路径
|
||||||
|
//
|
||||||
|
// 使用方法:
|
||||||
|
// app.listen_usockets(3000) // 使用 uSockets 后端
|
||||||
|
// app.listen(":3000") // 使用默认 picoev 后端
|
||||||
|
//
|
||||||
|
// 编译命令 (必须使用 -enable-globals):
|
||||||
|
// v -enable-globals -cc gcc -ldflags "-ldbghelp" your_app.v -o app.exe
|
||||||
|
//
|
||||||
|
// 性能对比 (200连接, 100K请求):
|
||||||
|
// uSockets: ~22,000 RPS (高并发优化)
|
||||||
|
// picoev: ~15,000 RPS
|
||||||
|
//
|
||||||
|
// 注意: uSockets 在高并发场景下优势明显 (~50% 提升)
|
||||||
|
// 低并发时两者性能相近
|
||||||
|
|
||||||
|
module hono
|
||||||
|
|
||||||
|
import usockets
|
||||||
|
import net.http
|
||||||
|
import strings
|
||||||
|
|
||||||
|
// uSockets 服务器配置
|
||||||
|
pub struct UsocketsConfig {
|
||||||
|
pub:
|
||||||
|
port int = 8080
|
||||||
|
host string = '0.0.0.0'
|
||||||
|
keepalive_timeout int = 30
|
||||||
|
max_keepalive_req int = 10000
|
||||||
|
}
|
||||||
|
|
||||||
|
// 全局变量存储应用引用 (需要 -enable-globals 编译选项)
|
||||||
|
__global g_usockets_app = &Hono(unsafe { nil })
|
||||||
|
__global g_usockets_config = UsocketsConfig{}
|
||||||
|
|
||||||
|
// 使用 uSockets 启动服务器
|
||||||
|
pub fn (mut app Hono) listen_usockets(port int) {
|
||||||
|
app.listen_usockets_with_config(UsocketsConfig{
|
||||||
|
port: port
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用 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
|
||||||
|
|
||||||
|
// 创建 uSockets 事件循环
|
||||||
|
loop := usockets.create_loop()
|
||||||
|
ctx := usockets.create_socket_context(loop)
|
||||||
|
|
||||||
|
// 设置回调
|
||||||
|
ctx.on_open(usockets_on_open)
|
||||||
|
ctx.on_data(usockets_on_data)
|
||||||
|
ctx.on_close(usockets_on_close)
|
||||||
|
ctx.on_writable(usockets_on_writable)
|
||||||
|
ctx.on_timeout(usockets_on_timeout)
|
||||||
|
ctx.on_end(usockets_on_end)
|
||||||
|
|
||||||
|
// 开始监听
|
||||||
|
listener := ctx.listen(config.port)
|
||||||
|
if listener.is_valid() {
|
||||||
|
host_str := if config.host == '' { '127.0.0.1' } else { config.host }
|
||||||
|
println('[v-hono] Listening on http://${host_str}:${config.port}/ (uSockets)')
|
||||||
|
loop.run()
|
||||||
|
} else {
|
||||||
|
eprintln('[v-hono] Failed to listen on port ${config.port}')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// uSockets 回调函数
|
||||||
|
fn usockets_on_open(s usockets.Socket, is_client int, ip &char, ip_length int) usockets.Socket {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usockets_on_data(s usockets.Socket, data &char, length int) usockets.Socket {
|
||||||
|
if g_usockets_app == unsafe { nil } {
|
||||||
|
s.write_bytes('HTTP/1.1 500 Internal Server Error\r\nContent-Length: 21\r\n\r\nInternal Server Error')
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析 HTTP 请求
|
||||||
|
raw_data := unsafe { tos(&u8(data), length) }
|
||||||
|
method, path, query_map, body := parse_http_request_usockets(raw_data)
|
||||||
|
|
||||||
|
if method.len == 0 {
|
||||||
|
s.write_bytes('HTTP/1.1 400 Bad Request\r\nContent-Length: 11\r\n\r\nBad Request')
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// 路由匹配 - 优先使用快速路由器
|
||||||
|
mut response_sent := false
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
// 优化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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回退到混合路由器
|
||||||
|
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)
|
||||||
|
|
||||||
|
// 优化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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 404 Not Found
|
||||||
|
if !response_sent {
|
||||||
|
mut hono_ctx := create_usockets_context(method, path, map[string]string{}, query_map, body)
|
||||||
|
|
||||||
|
if handler := g_usockets_app.not_found_handler {
|
||||||
|
response := handler(mut hono_ctx)
|
||||||
|
send_usockets_response(s, hono_ctx, response)
|
||||||
|
} else {
|
||||||
|
s.write_bytes('HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 9\r\nConnection: keep-alive\r\n\r\nNot Found')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usockets_on_close(s usockets.Socket, code int, reason voidptr) usockets.Socket {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usockets_on_writable(s usockets.Socket) usockets.Socket {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usockets_on_timeout(s usockets.Socket) usockets.Socket {
|
||||||
|
return s.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usockets_on_end(s usockets.Socket) usockets.Socket {
|
||||||
|
s.shutdown()
|
||||||
|
return s.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析 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 := ''
|
||||||
|
|
||||||
|
len := raw.len
|
||||||
|
if len == 0 {
|
||||||
|
return method, path, query_map, body
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 = raw[path_start..path_end]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 快速解析 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: parse_http_method_usockets(method)
|
||||||
|
url: path
|
||||||
|
data: body
|
||||||
|
}
|
||||||
|
params: params
|
||||||
|
query: query
|
||||||
|
body: body
|
||||||
|
url: path
|
||||||
|
path: path
|
||||||
|
status_code: 200
|
||||||
|
headers: map[string]string{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 快速 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()
|
||||||
|
|
||||||
|
// 优化3:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
|
||||||
|
for prefix in app.sorted_middleware_prefixes {
|
||||||
|
if path.starts_with(prefix) || prefix == '/' {
|
||||||
|
if mws := app.route_middlewares[prefix] {
|
||||||
|
middlewares << mws
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
mw := middlewares[idx]
|
||||||
|
return mw(mut ctx, fn [idx, middlewares, handler] (mut c Context) http.Response {
|
||||||
|
return exec_middlewares_usockets(idx + 1, middlewares, mut c, handler)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return handler.handle(mut ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送 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 }
|
||||||
|
|
||||||
|
mut resp := strings.new_builder(512)
|
||||||
|
|
||||||
|
// 状态行
|
||||||
|
resp.write_string('HTTP/1.1 ')
|
||||||
|
resp.write_string(status_code.str())
|
||||||
|
resp.write_string(' ')
|
||||||
|
resp.write_string(get_status_text_usockets(status_code))
|
||||||
|
resp.write_string('\r\n')
|
||||||
|
|
||||||
|
// 头部
|
||||||
|
mut has_content_type := false
|
||||||
|
for key, value in ctx.headers {
|
||||||
|
// 使用快速大小写不敏感比较
|
||||||
|
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_len == 12 && eq_ignore_case_usockets(key, 'content-type') {
|
||||||
|
has_content_type = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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')
|
||||||
|
has_content_type = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !has_content_type {
|
||||||
|
resp.write_string('Content-Type: text/plain; charset=utf-8\r\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Content-Length
|
||||||
|
resp.write_string('Content-Length: ')
|
||||||
|
resp.write_string(response.body.len.str())
|
||||||
|
resp.write_string('\r\n')
|
||||||
|
|
||||||
|
// Connection
|
||||||
|
resp.write_string('Connection: keep-alive\r\n')
|
||||||
|
|
||||||
|
// 空行 + body
|
||||||
|
resp.write_string('\r\n')
|
||||||
|
resp.write_string(response.body)
|
||||||
|
|
||||||
|
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 {
|
||||||
|
200 { 'OK' }
|
||||||
|
201 { 'Created' }
|
||||||
|
204 { 'No Content' }
|
||||||
|
301 { 'Moved Permanently' }
|
||||||
|
302 { 'Found' }
|
||||||
|
304 { 'Not Modified' }
|
||||||
|
400 { 'Bad Request' }
|
||||||
|
401 { 'Unauthorized' }
|
||||||
|
403 { 'Forbidden' }
|
||||||
|
404 { 'Not Found' }
|
||||||
|
405 { 'Method Not Allowed' }
|
||||||
|
500 { 'Internal Server Error' }
|
||||||
|
502 { 'Bad Gateway' }
|
||||||
|
503 { 'Service Unavailable' }
|
||||||
|
else { 'Unknown' }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
Module {
|
Module {
|
||||||
name: 'hono'
|
name: 'hono'
|
||||||
description: 'A high-performance V language web framework inspired by Hono.js, featuring hybrid routing, LRU cache, middleware support, and more.'
|
description: 'A high-performance V language web framework inspired by Hono.js, featuring hybrid routing, LRU cache, middleware support, and more.'
|
||||||
version: '0.3.4'
|
version: '0.3.9'
|
||||||
license: 'MIT'
|
license: 'MIT'
|
||||||
dependencies: []
|
dependencies: []
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user