Repository: nodejs/node
Pull request: http2: skip writeHead if stream is closed

Fixes: https://github.com/nodejs/node/issues/57416

This issue can be reproduced by destroying the session immediately after the client sends a request.
You may occasionally see an error after running it a few times.
``` sh
seq 100 | xargs -n1 -P100 node client.js
```

``` js
// server.js
const http2 = require('http2');
const server = http2.createServer((req, res) => {
  setTimeout(() => {
    res.writeHead(200, { 'content-type': 'text/plain' });
    res.end('Hello from HTTP/2 server!\n');
  }, 100); 
});

server.listen(6000, () => {});
```

``` js
// client.js
const http2 = require('http2');

const client = http2.connect('http://localhost:6000');
const req = client.request({ ':path': '/' });
setTimeout(() => {
    client.destroy();
}, 100);
```
If writeHead() is called after the server receives a GOAWAY frame but before it sends a RST_STREAM, the server may enter an error state.

After the GOAWAY frame is received, the http2Stream is immediately closed.
However, the response object (res) is only marked as closed after the RST_STREAM frame is sent.

Currently, writeHead() checks whether the response object is closed, but it does not check whether the stream itself has been closed.



### how to fix
Even if the RST_STREAM frame hasn't been sent yet, it seems like it might already be queued when the http2Stream is closed.
So this change skips writeHead() when the stream is already closed.
<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: lib/internal/http2/compat.js
patch: @@ -706,7 +706,7 @@ class Http2ServerResponse extends Stream {
   writeHead(statusCode, statusMessage, headers) {
     const state = this[kState];
 
-    if (state.closed || this.stream.destroyed)
+    if (state.closed || this.stream.destroyed || this.stream.closed)
       return this;
     if (this[kStream].headersSent)
       throw new ERR_HTTP2_HEADERS_SENT();

filename: test/parallel/test-http2-compat-write-head-after-close.js
patch: @@ -0,0 +1,23 @@
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto) { common.skip('missing crypto'); };
+const h2 = require('http2');
+
+const server = h2.createServer((req, res) => {
+  const stream = req.stream;
+  stream.close();
+  res.writeHead(200, { 'content-type': 'text/plain' });
+});
+
+server.listen(0, common.mustCall(() => {
+  const port = server.address().port;
+  const client = h2.connect(`http://localhost:${port}`);
+  const req = client.request({ ':path': '/' });
+  req.on('response', common.mustNotCall('head after close should not be sent'));
+  req.on('end', common.mustCall(() => {
+    client.close();
+    server.close();
+  }));
+  req.end();
+}));