服务器计时
Server-Timing 是 Performance API 的一部分,它允许服务器将请求-响应周期相关的指标传达给用户代理。您可以像处理所有其他 Performance API 指标一样,收集此信息并根据服务器端指标采取行动。
发送服务器指标
Server-Timing HTTP 标头用于展示任何后端服务器时序指标。例如,您可能希望发送数据库读/写操作时间、CPU 时间和文件系统访问时间。
您可以发送带值或不带值的指标。指标可以包含可选的描述。建议尽可能保持名称、描述和数据简短,以最小化 HTTP 开销。
Server-Timing 标头示例
// Single metric without value
Server-Timing: missedCache
// Single metric with value
Server-Timing: cpu;dur=2.4
// Single metric with description and value
Server-Timing: cache;desc="Cache Read";dur=23.2
// Two metrics with values
Server-Timing: db;dur=53, app;dur=47.2
// Server-Timing as trailer
Trailer: Server-Timing
--- response body ---
Server-Timing: total;dur=123.4
要计算实际的服务器端指标,请查阅您的服务器端 CMS、框架或编程语言的文档,了解如何在后端应用程序中测量性能。如果您的服务器使用 Node.js,那么性能测量 API 将非常类似于浏览器中的 Performance API。这是因为 Node.js 的性能模块是 W3C Web Performance API 的一个子集,并包含用于 Node.js 特定的性能测量的额外 API。有关更多信息,请参阅 Node.js 性能文档。
请注意,服务器、客户端和任何中间代理之间没有时钟同步。这意味着,如果您的服务器发送时间戳或 startTime,该值可能无法有意义地映射到客户端时间轴的 startTime。
在计算出所需的指标后,服务器需要在其响应中发送 Server-Timing 标头。有关如何在 Node.js 中发送此标头的示例,请参阅 Server-Timing 参考页面。
检索服务器指标
服务器时序指标通常会出现在浏览器的开发者工具中,但它们也作为 PerformanceServerTiming 性能条目存储,您可以像访问其他 性能数据一样访问它们。但是,没有单独的 "server-timing" 条目。PerformanceServerTiming 对象可以从 "navigation" 和 "resource" 性能条目中观察到。您可以通过 PerformanceResourceTiming.serverTiming 属性访问服务器指标,该属性是 PerformanceServerTiming 对象的一个数组。
给定一个如下所示的 Server-Timing 标头
Server-Timing: cache;desc="Cache Read";dur=23.2,db;dur=53,app;dur=47.2
使用以下代码,PerformanceObserver 可以在客户端记录这些条目
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
entry.serverTiming.forEach((serverEntry) => {
console.log(
`${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`,
);
// Logs "cache (Cache Read) duration: 23.2"
// Logs "db () duration: 53"
// Logs "app () duration: 47.2"
});
});
});
["navigation", "resource"].forEach((type) =>
observer.observe({ type, buffered: true }),
);
隐私和安全注意事项
Server-Timing 标头可能会暴露潜在敏感的应用程序和基础设施信息。因此,您需要在服务器端控制何时以及向谁返回这些指标。例如,您可以只向已通过身份验证的用户显示指标,而对公众不显示任何内容。
PerformanceServerTiming 接口仅限于同源策略,但您可以使用 Timing-Allow-Origin 标头来指定允许访问服务器指标的域名。另外,请注意,此接口在某些浏览器中仅在安全上下文 (HTTPS) 中可用。