nodejs / nodejs/node

AsyncLocalStorage instance shared between several http requests

未关闭
#41,978 16 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

async_hooks
主要语言
JavaScript
星标
122k
派生
37.3k
平均合并
4 天 2 小时
30 天内合并 PR
283

描述

Version

v17.5.0

Platform

Linux DESKTOP 5.10.60.1-microsoft-standard-WSL2 #1 SMP Wed Aug 25 23:20:18 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Subsystem

async_hooks

What steps will reproduce the bug?

Opening localhost:3000/ in Chrome (keep-alive) shows that we have access to the same instance of AsyncLocalStorage when we serve both / and /favicon.ico. I would understand if both of them were coming from the same async resource representing connection and there was no distinction, but log (see below) produced by async hooks shows that there was two separate HTTPINCOMINGMESSAGE but when it comes to request listener suddenly we have same asyncId.

May be it is not a bug, but observed behavior is very confusing. I've read that

import * as http from "node:http";
import * as events from "node:events";
import * as async_hooks from "node:async_hooks";

await events.once(http.createServer(httpHandler).listen(3000), "listening");
console.log("server started");
const currentRequest = new async_hooks.AsyncLocalStorage();

// Create hook to ensure t
async_hooks
  .createHook({
    init(asyncId, type) {
      if (type === "TickObject" || type === "TickTimeout") return;
      console.log(asyncId, type);
    },
  })
  .enable();

function getCurrentRequestExn() {
  const current = currentRequest.getStore();
  if (!current) throw new Error("no current request");
  return current;
}

function setCurrentRequest(req) {
  console.log(
    "setCurrentRequest %s %d",
    req.url,
    async_hooks.executionAsyncId()
  );
  const existing = currentRequest.getStore();
  if (existing !== void 0) throw new Error("current request already set");
  currentRequest.enterWith(req);
}

function httpHandler(req, res) {
  setCurrentRequest(req);
  if (req.url === "/") res.end(route1());
  else if (req.url === "/favicon.ico") res.end(route2());
}

function route1() {
  const req = getCurrentRequestExn();
  return "route1 " + req.url;
}

function route2() {
  const req = getCurrentRequestExn();
  return "route2" + req.url;
}

Log produced:

server started
20 TCPWRAP
22 HTTPINCOMINGMESSAGE
24 TCPWRAP
26 HTTPINCOMINGMESSAGE
setCurrentRequest / 22
29 Timeout
34 Timeout
setCurrentRequest /favicon.ico 22

And, since we accessing same instance of the async local storage - then there is an exception:

file:///home/dolphin/projects/komsomol/server.js:33
  if (existing !== void 0) throw new Error("current request already set");
                           ^

Error: current request already set
    at setCurrentRequest (file:///home/dolphin/projects/komsomol/server.js:33:34)
    at Server.httpHandler (file:///home/dolphin/projects/komsomol/server.js:38:3)
    at Server.emit (node:events:526:28)
    at parserOnIncoming (node:_http_server:951:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
How often does it reproduce? Is there a required condition?

All the time.

What is the expected behavior?

Separate instances of AsyncLocalStorage for each request, or some explanation in documentation on how to achieve it.

What do you see instead?

Same instances of AsyncLocalStorage shared between http requests contexts when requests made using keep-alive connection.

Additional information

No response

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先,在保持浏览器连接 keep-alive 的情况下运行 server.js 中的复现,并比较两个请求的 async_hooks 输出。然后,跟踪请求经过 node:_http_server 中 parserOnIncoming 的路径,以及 issue 中描述的 AsyncLocalStorage 行为。当请求上下文能够被正确区分,或已记录受支持的行为和所需的用法时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, nodejs
领域
backend
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
冷清
描述清晰度
基本清楚
新手友好度
48/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。