Effinitive Webserver 在 TechEmpower FrameworkBenchmarks 中的 .NET 10 基准测试实现解析
Effinitive Webserver 在 TechEmpower FrameworkBenchmarks 中的 .NET 10 基准测试实现解析
本文以 effinitive 测试目录 为主线,系统解析 Effinitive Webserver 如何以 C# 14.0 + .NET 10 技术栈参与 TechEmpower FrameworkBenchmarks 的 plaintext 与 json 两个测试:包括入口程序、端点实现、HTTP 合规中间件、项目编译配置、Docker 构建流程以及 benchmark_config.json / config.toml 的元数据语义,并对照 TFB 工具链的验证逻辑说明每个实现细节背后的验收标准。读完本文,你将能完整复现该测试的构建、运行与验证流程。
一、测试实现概览
effinitive 是 TechEmpower FrameworkBenchmarks(TFB)为 Effinitive Webserver,仅覆盖两个无需数据库的测试类型:
| 测试类型 | 路由 | 返回内容 |
|---|---|---|
| Plaintext | /plaintext |
Hello, World!(text/plain) |
| JSON | /json |
{"message":"Hello, World!"}(application/json) |
对应的基础设施版本(原文档声明)为:
- 语言:C# 14.0
- 平台:.NET 10
- Web Server:Effinitive Webserver(通过 NuGet 包
EffinitiveFramework.Core1.2.0 引入)
该实现是典型的 "Realistic / Fullstack / Raw ORM / 无数据库" 场景:由 Effinitive 自身同时承担 Web Server 与业务逻辑层的职责,因此 benchmark_config.json 中 webserver 与 framework 字段均指向 Effinitive。
二、入口程序:应用装配与生命周期管理
测试的启动入口位于 Benchmarks/Program.cs,核心是使用 Fluent API 组装 Effinitive 应用:
var app = EffinitiveApp.Create()
.UsePort(8080)
.MapEndpoints()
.UseMiddleware<HttpComplianceMiddleware>()
.Build();
几个关键点值得展开:
UsePort(8080):显式绑定 8080 端口,这与 effinitive.dockerfile 中的EXPOSE 8080、benchmark_config.json 中的"port": 8080三者保持一致,是 TFB 探测被测应用的固定端口约定。MapEndpoints():将项目中继承NoRequestEndpointBase<T>的端点类自动注册到路由表(下文详述)。UseMiddleware<HttpComplianceMiddleware>():挂载 HTTP 合规中间件,补齐响应头以满足 TFB 的响应头校验。
生命周期管理上,程序通过 ManualResetEvent 阻塞主线程,并在 AppDomain.CurrentDomain.ProcessExit 事件中置位事件使进程优雅退出;任何未捕获异常都会打印堆栈并返回退出码 -1,便于在容器日志中排查启动失败。
三、端点实现:声明式无请求端点
两个端点均基于 Effinitive 的 NoRequestEndpointBase<T> 抽象基类,通过覆写属性与 HandleAsync 方法即可完成路由、方法与响应的声明。
Plaintext 端点
文件:Benchmarks/Benchmarks/Plaintext.cs
public class Plaintext : NoRequestEndpointBase<string>
{
protected override string Method => "GET";
protected override string Route => "/plaintext";
protected override string ContentType => "text/plain";
public override ValueTask<string> HandleAsync(CancellationToken cancellationToken = default)
{
return ValueTask.FromResult("Hello, World!");
}
}
JSON 端点
文件:Benchmarks/Benchmarks/Json.cs
public class JsonResult
{
public string Message { get; set; }
}
public class Json : NoRequestEndpointBase<JsonResult>
{
protected override string Method => "GET";
protected override string Route => "/json";
protected override string ContentType => "application/json; charset=utf-8";
public override ValueTask<JsonResult> HandleAsync(CancellationToken cancellationToken = default)
{
return ValueTask.FromResult(new JsonResult() { Message = "Hello, World!" });
}
}
对照 TFB 的验收脚本可以确认这两处设计的合规性(详见 toolset/test_types/verifications.py):
- 正文:plaintext 校验要求响应体(不区分大小写)包含
hello, world!;json 校验要求反序列化后的对象包含键message且值为hello, world!(大小写不敏感)。两端点的返回值与之完全吻合。 - Content-Type:json 测试要求匹配
^application/json(; ?charset=(UTF|utf)-8)?$,plaintext 测试要求匹配^text/plain(; ?charset=(UTF|utf)-8)?$。Json.cs显式携带; charset=utf-8,Plaintext.cs使用裸text/plain,两者都在合法范围内。 - 性能考量:两端点返回的是编译期常量,
ValueTask.FromResult直接完成,无异步调度开销、无额外 JSON 序列化配置,是最小化响应体积的写法。
四、HTTP 合规中间件:补齐 Server 与 Date 响应头
文件:Benchmarks/HttpComplianceMiddleware.cs
public class HttpComplianceMiddleware : IMiddleware
{
public async ValueTask<HttpResponse> InvokeAsync(HttpRequest request, RequestDelegate next, CancellationToken cancellationToken)
{
var response = await next(request, cancellationToken);
response.Headers.Add("Server", "Effinitive/1.1");
response.Headers.Add("Date", DateTime.UtcNow.ToString("r"));
return response;
}
}
该中间件的存在并非多余装饰,而是直接回应 TFB 验证逻辑的硬性要求。在 verifications.py 的 verify_headers 中:
- 必选头检查:
Server、Date、Content-Type三者缺失任一即为fail; - Date 头格式检查:必须匹配
%a, %d %b %Y %H:%M:%S %Z(RFC 1123 格式),DateTime.UtcNow.ToString("r")恰好输出该格式; - Date 头新鲜度检查:验证逻辑会间隔 3 秒发起第二次请求,若两次响应的
Date相同则判定为缓存失效而fail,因此中间件必须基于DateTime.UtcNow实时生成; - 长度头检查:
Content-Length与Transfer-Encoding至少出现其一(由 Effinitive 框架底层自动补充)。
由此可以理解中间件取名 "HttpCompliance" 的含义——它保证被测响应在功能正确之外,还能通过 TFB 的协议级合规审计。
五、项目编译配置:为基准测试量身定制
文件:Benchmarks/Benchmarks.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<AssemblyTitle>Effinitive Benchmarks</AssemblyTitle>
<Description>Test suite to be executed with TechEmpower FrameworkBenchmarks.</Description>
<StartupObject>Benchmarks.Program</StartupObject>
<OutputType>Exe</OutputType>
<ServerGarbageCollection>true</ServerGarbageCollection>
<TieredCompilation>false</TieredCompilation>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EffinitiveFramework.Core" Version="1.2.0" />
</ItemGroup>
</Project>
各配置项的基准测试语义:
TargetFramework=net10.0+LangVersion=14.0:对应原文档声明的 ".NET 10" 与 "C# 14.0" 版本要求,同时与 effinitive.dockerfile 使用的 SDK 镜像mcr.microsoft.com/dotnet/sdk:10.0-alpine匹配。ServerGarbageCollection=true:启用服务器 GC,以多线程、多核为优先目标,减少单核停顿,适合高并发 Web 负载。TieredCompilation=false:关闭分层编译,让方法在首次调用即编译为优化代码,避免基准测试热身后仍运行低质量 tier 0 代码而引入测量噪声。StartupObject=Benchmarks.Program:显式指定可执行入口。
六、Docker 镜像构建:Alpine 自包含发布
FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build
WORKDIR /source
# copy csproj and restore as distinct layers
COPY Benchmarks/*.csproj .
RUN dotnet restore -r linux-musl-x64
# copy and publish app and libraries
COPY Benchmarks/ .
RUN dotnet publish -c release -o /app -r linux-musl-x64 --no-restore --self-contained
# final stage/image
FROM mcr.microsoft.com/dotnet/runtime-deps:10.0-alpine
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./Benchmarks"]
EXPOSE 8080
该 Dockerfile 采用了多阶段构建,细节上处处为基准测试服务:
- 先拷贝 csproj 再
dotnet restore:利用 Docker 层缓存,源码未变化时复用依赖恢复层,加快迭代构建; -r linux-musl-x64 --self-contained:面向 Alpine 的 musl libc 发布自包含程序,将 .NET 运行时一起打包,因此最终阶段可以基于不含 .NET 运行时的runtime-deps:10.0-alpine精简镜像,减小容器体积与启动时间;ENTRYPOINT ["./Benchmarks"]:直接以发布产物作为容器入口,无脚本中间层。
七、基准配置与元数据语义
benchmark_config.json
文件:frameworks/CSharp/effinitive/benchmark_config.json
{
"framework": "effinitive",
"maintainers": ["HBartosch"],
"tests": [{
"default": {
"plaintext_url": "/plaintext",
"json_url": "/json",
"port": 8080,
"approach": "Realistic",
"classification": "Fullstack",
"database": "None",
"framework": "Effinitive",
"language": "C#",
"orm": "Raw",
"platform": ".NET",
"webserver": "Effinitive",
"os": "Linux",
"database_os": "Linux",
"display_name": "Effinitive Webserver",
"notes": ""
}
}]
}
该文件是 TFB 工具链识别与驱动测试的"契约"。关键字段含义:
plaintext_url/json_url:被测端点路径。TFB 的 plaintext 测试类型 会校验该 URL 长度不小于 10 个字符,json 测试类型 则校验不小于 5 个字符——/plaintext(10 字符)与/json(5 字符)恰好满足各自下限,且与 Benchmarks 目录 中两个端点的Route一一对应。approach=Realistic、classification=Fullstack:描述测试风格与实现层次——使用完整 Web 框架栈而非纯 Socket 手写服务器。database=None、orm=Raw:本测试不涉及数据库,故 ORM 标注为Raw(无 ORM)。port=8080:与Program.cs的UsePort(8080)及 Dockerfile 的EXPOSE 8080三方一致。
config.toml
文件:frameworks/CSharp/effinitive/config.toml 以 TOML 形式记录了与 benchmark_config.json 基本对应的元数据:
[framework]
name = "effinitive"
[main]
urls.plaintext = "/plaintext"
urls.json = "/json"
approach = "Realistic"
classification = "Fullstack"
database = "None"
database_os = "Linux"
os = "Linux"
orm = "Raw"
platform = ".NET"
webserver = "Effinitive"
versus = "None"
两者配合使用:benchmark_config.json 是工具链执行测试与采集结果的主要依据,config.toml 提供面向站点展示的框架元信息。
八、与 TFB 工具链的联动:验证与压测流程
TFB 工具链(toolset)通过 AbstractTestType 机制读取 benchmark_config.json 中对应的 *_url 键,进而对被测实现执行两阶段流程:
- 验证阶段(verify):由 json.py 与 plaintext.py 发起请求,依次执行正文校验(
basic_body_verification、verify_helloworld_object)、状态码校验(期望 200)与响应头校验(verify_headers)。Effinitive 实现正是为了通过上述校验而设置了两端点内容、Content-Type 与中间件补齐的响应头。 - 压测阶段:plaintext 使用 toolset/wrk/pipeline.sh(带管道深度 16 的 wrk 脚本),json 使用 toolset/wrk/concurrency.sh,按配置的并发档位与时长施压并采集延迟分布。
九、本地验证方法
在已安装 Docker 的环境中,可在仓库根目录运行 TFB 入口脚本(tfb)对 Effinitive 实现做快速验证:
./tfb --mode verify --test effinitive
verify 模式不会记录基准数据,只会构建 effinitive.dockerfile 镜像、启动容器并对 /plaintext、/json 两个端点做协议合规校验。若要观察实际吞吐,可将 --mode 切换为 benchmark,并配合 --test effinitive 限定只跑该实现。
十、小结
Effinitive 的 TFB 测试实现是一个"小而完整"的参考样本:以 C# 14.0 / .NET 10 / EffinitiveFramework.Core 1.2.0 为技术栈,通过 NoRequestEndpointBase<T> 声明两个端点、通过 HttpComplianceMiddleware 满足响应头合规、通过关闭分层编译与开启服务器 GC 优化运行时表现,再经由多阶段 Alpine 自包含镜像接入 TFB 的验证与压测流水线。其代码布局与配置文件的对应关系(端口 8080、路由 /plaintext//json、元数据字段)也展示了 TFB 框架接入的通用模式,可作为自行编写 TFB 测试实现的参照。