https.Agent在Node中的作用是什么?

What is the role of https.Agent in Node?

在节点https module docs中, 关于https.request,举个例子:

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
options.agent = new https.Agent(options);

const req = https.request(options, (res) => {
  // ...
});

这个例子在我看来有点模棱两可,我问过 SO question regarding this ambiguity and following a comment reaffirming the strange wording, opened an issue for this.

无论如何,我仍在尝试了解代理在这种情况下扮演的角色,因为 https.Agent 模块确实接受 TLS 连接选项:

interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions

https.Agent对象的定义是:

An Agent object for HTTPS similar to http.Agent.

http.Agent 对象的定义是:

An Agent is responsible for managing connection persistence and reuse for HTTP clients.

由此我了解到,代理是 'in charge' 管理连接 - 显然,https.Agent 存在于 'plain' http.Agent 之上将暗示它是 'in charge' 管理 HTTPS 连接 - 因此它可能收到 TLS 配置选项。

我的问题是 - 这是否意味着在这种情况下代理有额外的责任来配置请求的网络安全?如果这是真的,这是一个奇怪的 API - 我本希望在 https.request 的单独密钥上看到网络连接配置(如上面代码片段后的示例所示)。为什么要为另一个职责重载同一个对象?真的,为什么要有 https.Agent 呢? http.Agent 应该控制连接池和保持连接活动,而另一层应该控制配置实际请求。 https.Agent 对象对我来说似乎定义不明确。

其实是HTTPS doc points to some good resources, it also contains a link to HTTPS module source code,里面透露了很多。但要回答你的问题:

does this mean that the Agent in this case has an added responsibility of configuring the network security of the requests

是的,您的 HTTPS 代理可以执行自定义安全功能,甚至可以使用外部 HTTPS 实现,但是对于 built-in https.Agent,使用本机 TLS 模块,并且您可以选择传递给构造函数的是 ultimately passed to tls.connect,允许您配置自定义 TLS 选项。

Why overload the same object for another responsibility? Really, why have an https.Agent at all?

因为 HTTPS 在 TLS 上运行。实际上 https.Agent 内部调用和构造 http.Agent。额外的位主要是在 TCP “套接字”上使用 SSL “会话”,如果你搜索 getName in https.Agent source and compare that to http.Agent's,你会发现 SSL 会话缓存基于更多字段,如 DHparams、客户端证书等。对于 HTTP 根本不存在。