h2lean 0.19.7 → 0.19.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,24 +22,17 @@
22
22
  // reports 'finish' on both stacks.
23
23
  // * the order of the teardown events differs: node reports the request's
24
24
  // events (its 'end', its 'aborted', its 'close') before the response's
25
- // ('finish', then 'close'), h2lean reports the response's first. Every
26
- // event fires on both stacks -- measured against a live node server over
27
- // the four shapes of bench/micro/probe-teardown-order.js, the sets are equal -- and
28
- // only their order within the teardown turn differs. One pair is not a
29
- // fixed difference at all: the request's 'end' against the 'aborted'
30
- // depends on whether the peer's END_STREAM and its reset arrive in one
31
- // read or in two, and the two stacks order that pair differently.
25
+ // ('finish', then 'close'), h2lean can report the response's 'finish'
26
+ // first, at end() rather than at the stream close. Every event fires on
27
+ // both stacks -- measured against a live node server over the four shapes
28
+ // of bench/micro/probe-teardown-order.js, the sets are equal -- and only
29
+ // their order within the teardown turn differs. One pair is not a fixed
30
+ // difference at all: the request's 'end' against the 'aborted' depends on
31
+ // whether the peer's END_STREAM and its reset arrive in one read or in
32
+ // two, and the two stacks order that pair differently.
32
33
  // * the body is pulled, not pushed: nothing is read off the wire until the
33
34
  // application consumes it, so an unread upload applies backpressure to the
34
35
  // sender (node does the same) instead of buffering here.
35
- // * a stream 'error' reaches the compat request: onRequestError destroys req
36
- // with it, so an application that listens only on res gets an unhandled
37
- // 'error'. node's onStreamError (internal/http2/compat.js) is purposefully
38
- // blank -- "errors in compatibility mode are not forwarded to the request
39
- // and response objects". Measured with a content-length promise broken by a
40
- // short body (content-length 10, two octets sent): node reports st-error
41
- // then st-close:1 and the client its own error/close:1, h2lean reports
42
- // st-close:1, st-error, then an uncaught ERR_HTTP2_STREAM_ERROR out of req.
43
36
  // * with the server option shareHeaders:true, req.headers is frozen and shared
44
37
  // between requests whose header block is identical, so req.url = ... and
45
38
  // req.method = ... throw instead of rewriting the request.
@@ -55,6 +48,34 @@
55
48
  const { Readable, Stream } = require('node:stream');
56
49
 
57
50
  const { nullProto, trimName, isFieldName } = require('../headers');
51
+ const { kCompatSocket } = require('../Http2Stream');
52
+ const { NO_ERROR } = require('../frames');
53
+ const { Http2ServerStream } = require('./Http2ServerStream');
54
+
55
+ // A peer reset and a teardown the application starts reach the stream's
56
+ // _destroy with different arguments (sendRst true for the latter; session
57
+ // destroy sets session.destroyed before it destroys its streams). node's
58
+ // request sees 'close' before the queued EOF only for the local teardown;
59
+ // a peer reset that is not an error has its EOF delivered first. Mark the
60
+ // local case at the point the two shapes are still distinct. One wrapper at
61
+ // module load, one boolean write on a stream that is being destroyed -- the
62
+ // per-request dispatch path stays untouched.
63
+ const originalStreamDestroy = Http2ServerStream.prototype._destroy;
64
+ Http2ServerStream.prototype._destroy = function compatTrackedDestroy(code, sendRst, error) {
65
+ const req = this._request;
66
+ if (req !== undefined && (sendRst ||
67
+ (this.session !== undefined && this.session.destroyed))) {
68
+ req._localTeardown = true;
69
+ }
70
+ return originalStreamDestroy.call(this, code, sendRst, error);
71
+ };
72
+
73
+ // The inbound trailers callback on node carries (trailers, flags, rawTrailers).
74
+ // The session hands the flat raw field list over on this private event first,
75
+ // because a stream's compat dispatch forwards one argument; a symbol keeps the
76
+ // event off the application-visible names. Symbol.for keeps the two modules in
77
+ // step without an extra require on the session's hot path.
78
+ const kCompatRawTrailers = Symbol.for('h2lean.compat.rawTrailers');
58
79
 
59
80
  function err(code, msg) {
60
81
  const e = new Error(msg);
@@ -62,6 +83,99 @@ function err(code, msg) {
62
83
  return e;
63
84
  }
64
85
 
86
+ // node's compat `req.socket`/`res.socket` is a Proxy over the STREAM (a different
87
+ // handler from session.socket's core.js one): write/read/pause/resume throw,
88
+ // end/emit/destroy route to the stream, everything else falls through to the
89
+ // transport socket. The stream reserves the slot at construction (Http2Stream.js's
90
+ // kCompatSocket), so the first read only creates the Proxy and fills it; req and
91
+ // res share one object and a handler that never reads either pays no allocation.
92
+ // Ported from node's proxySocketHandler (internal/http2/compat.js).
93
+ const NO_SOCKET_MANIPULATION = 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)';
94
+ const compatSocketHandler = {
95
+ has(stream, prop) {
96
+ const ref = stream.session !== undefined ? stream.session._socket : stream;
97
+ return (prop in stream) || (prop in ref);
98
+ },
99
+ get(stream, prop) {
100
+ switch (prop) {
101
+ case 'on':
102
+ case 'once':
103
+ case 'end':
104
+ case 'emit':
105
+ case 'destroy':
106
+ return stream[prop].bind(stream);
107
+ case 'writable':
108
+ case 'destroyed':
109
+ return stream[prop];
110
+ case 'readable':
111
+ return stream.destroyed ? false : stream.readable;
112
+ case 'setTimeout': {
113
+ const session = stream.session;
114
+ return session !== undefined
115
+ ? session.setTimeout.bind(session) : stream.setTimeout.bind(stream);
116
+ }
117
+ case 'write':
118
+ case 'read':
119
+ case 'pause':
120
+ case 'resume':
121
+ throw err('ERR_HTTP2_NO_SOCKET_MANIPULATION', NO_SOCKET_MANIPULATION);
122
+ default: {
123
+ const session = stream.session;
124
+ const ref = session !== undefined ? session._socket : stream;
125
+ const value = ref[prop];
126
+ return typeof value === 'function' ? value.bind(ref) : value;
127
+ }
128
+ }
129
+ },
130
+ getPrototypeOf(stream) {
131
+ const session = stream.session;
132
+ return Reflect.getPrototypeOf(session !== undefined ? session._socket : stream);
133
+ },
134
+ set(stream, prop, value) {
135
+ switch (prop) {
136
+ case 'writable':
137
+ case 'readable':
138
+ case 'destroyed':
139
+ case 'on':
140
+ case 'once':
141
+ case 'end':
142
+ case 'emit':
143
+ case 'destroy':
144
+ stream[prop] = value;
145
+ return true;
146
+ case 'setTimeout': {
147
+ const session = stream.session;
148
+ if (session !== undefined) {
149
+ session.setTimeout = value;
150
+ } else {
151
+ stream.setTimeout = value;
152
+ }
153
+ return true;
154
+ }
155
+ case 'write':
156
+ case 'read':
157
+ case 'pause':
158
+ case 'resume':
159
+ throw err('ERR_HTTP2_NO_SOCKET_MANIPULATION', NO_SOCKET_MANIPULATION);
160
+ default: {
161
+ const session = stream.session;
162
+ const ref = session !== undefined ? session._socket : stream;
163
+ ref[prop] = value;
164
+ return true;
165
+ }
166
+ }
167
+ }
168
+ };
169
+
170
+ function compatSocket(stream) {
171
+ let proxy = stream[kCompatSocket];
172
+ if (proxy === null) {
173
+ proxy = new Proxy(stream, compatSocketHandler);
174
+ stream[kCompatSocket] = proxy;
175
+ }
176
+ return proxy;
177
+ }
178
+
65
179
  // node's Link validation for writeEarlyHints (internal/validators.js:528-583,
66
180
  // v26.12.1): a string, or an array of strings joined with ', ', each matching the
67
181
  // link-value grammar `</...>; params`. The regex is node's own linkValueRegExp.
@@ -193,12 +307,11 @@ function onRequestEnd() {
193
307
  req.push(null);
194
308
  }
195
309
 
196
- function onRequestError(error) {
197
- const req = this._request;
198
- if (req !== undefined) {
199
- req.destroy(error);
200
- }
201
- }
310
+ // node's onStreamError (internal/http2/compat.js:160, v26.12.1) is purposefully
311
+ // blank: errors in compatibility mode are not forwarded to the request or the
312
+ // response. The subscription itself stays -- a stream the application never
313
+ // listens to must not throw on an unhandled 'error'.
314
+ function onRequestError() {}
202
315
 
203
316
  function onRequestAborted() {
204
317
  const req = this._request;
@@ -209,12 +322,29 @@ function onRequestAborted() {
209
322
  req.emit('aborted');
210
323
  }
211
324
 
325
+ function onRequestRawTrailers(raw) {
326
+ const req = this._request;
327
+ if (req !== undefined) {
328
+ this._rawTrailerFields = raw;
329
+ }
330
+ }
331
+
212
332
  function onRequestTrailers(trailers) {
213
333
  const req = this._request;
214
334
  if (req === undefined) {
215
335
  return;
216
336
  }
217
- req._trailers = trailers;
337
+ // node's onStreamTrailers (internal/http2/compat.js:145) merges into the
338
+ // request's own plain object and spreads the flat raw pair list, in wire
339
+ // order, into its own rawTrailers array.
340
+ Object.assign(req._trailers, trailers);
341
+ const raw = this._rawTrailerFields;
342
+ if (raw !== undefined) {
343
+ for (let i = 0; i < raw.length; i += 2) {
344
+ req._rawTrailers.push(raw[i], raw[i + 1]);
345
+ }
346
+ this._rawTrailerFields = undefined;
347
+ }
218
348
  req.emit('trailers', trailers);
219
349
  }
220
350
 
@@ -237,20 +367,28 @@ function onRequestClose() {
237
367
  if (!req._didRead) {
238
368
  req.resume();
239
369
  }
240
- // 'close' after 'end', so queue it behind the end the push above scheduled.
241
- // node emits it right here instead, so the two stacks differ in the order of
242
- // these two: see the difference list at the top of this file.
243
- req._tick(emitCloseNT, req);
244
- }
245
-
246
- function emitCloseNT(target) {
247
- target.emit('close');
370
+ // node's onStreamCloseRequest (internal/http2/compat.js:282) emits 'close'
371
+ // in the same turn as the stream close, before the queued EOF reaches the
372
+ // reader, for a local teardown or a reset carrying a code. A peer's NO_ERROR
373
+ // reset still delivers the owed EOF first (measured on 24 and 26), so that
374
+ // shape keeps the deferred close and reports readableEnded true; using the
375
+ // stream's own reset code rather than whether EOF happened to be emitted
376
+ // keeps the rule the same when the two teardown paths share a turn.
377
+ if (req._localTeardown || this.rstCode !== NO_ERROR) {
378
+ req.emit('close');
379
+ } else {
380
+ req._tick(emitCloseNT, req);
381
+ }
248
382
  }
249
383
 
250
384
  function emitFinishNT(target) {
251
385
  target.emit('finish');
252
386
  }
253
387
 
388
+ function emitCloseNT(target) {
389
+ target.emit('close');
390
+ }
391
+
254
392
  function onRequestTimeout() {
255
393
  const req = this._request;
256
394
  if (req !== undefined && !req._closed) {
@@ -275,6 +413,9 @@ function compatDispatch(name, arg) {
275
413
  // closing it here would report the 'close' without the 'finish' and
276
414
  // before the request's own 'close'.
277
415
  break;
416
+ case kCompatRawTrailers:
417
+ onRequestRawTrailers.call(this, arg);
418
+ break;
278
419
  case 'trailers':
279
420
  onRequestTrailers.call(this, arg);
280
421
  break;
@@ -316,7 +457,10 @@ class Http2ServerRequest extends Readable {
316
457
  this._method = stream._reqMethod;
317
458
  this._path = stream._reqPath;
318
459
  this._rawHeaders = undefined;
319
- this._trailers = { __proto__: null };
460
+ // node's request constructor uses a plain object for trailers (compat.js:323),
461
+ // unlike the null-prototype header maps; the incoming case variants are
462
+ // merged into it, not made the request's map.
463
+ this._trailers = {};
320
464
  this._rawTrailers = [];
321
465
  this._closed = false;
322
466
  this._ended = false;
@@ -396,15 +540,11 @@ class Http2ServerRequest extends Readable {
396
540
  return '2.0';
397
541
  }
398
542
 
399
- // node hands `req.socket` a Proxy over the *stream* (compat.js proxySocketHandler, distinct
400
- // from session.socket's core handler): write/read/pause/resume throw, end/emit/destroy route
401
- // to the stream. h2lean instead hands out the real socket -- it is smaller and answers the
402
- // same questions (remoteAddress), but a `.write()` that node refuses succeeds here. KNOWN
403
- // DIVERGENCE, and separate from the session surface. The session reference is cleared when the
404
- // stream dies (lib/Http2Stream.js _destroy, node core.js:2546), so the socket goes with it.
543
+ // node's IncomingMessage keeps its socket after the stream dies (only its
544
+ // ServerResponse drops it), so the proxy is returned unconditionally and is
545
+ // cached on the stream from the first read -- lazy, and one object per stream.
405
546
  get socket() {
406
- const session = this._stream.session;
407
- return session === undefined ? undefined : session._socket;
547
+ return compatSocket(this._stream);
408
548
  }
409
549
  get connection() {
410
550
  return this.socket;
@@ -414,11 +554,20 @@ class Http2ServerRequest extends Readable {
414
554
  return this._headers !== undefined ? this._headers[':method'] : this._method;
415
555
  }
416
556
  set method(method) {
557
+ // node's setter runs validateString(method, 'method') and then
558
+ // ERR_INVALID_ARG_VALUE('method', method) (internal/http2/compat.js:411).
559
+ // Both are TypeError instances; the message text is measured off the
560
+ // running binary, not paraphrased.
417
561
  if (typeof method !== 'string') {
418
- throw err('ERR_INVALID_ARG_TYPE', 'method must be a string');
562
+ const e = new TypeError(
563
+ `The "method" argument must be of type string. Received ${describeType(method)}`);
564
+ e.code = 'ERR_INVALID_ARG_TYPE';
565
+ throw e;
419
566
  }
420
567
  if (method.trim() === '') {
421
- throw err('ERR_INVALID_ARG_VALUE', 'method must not be empty');
568
+ const e = new TypeError(`The argument 'method' is invalid. Received ${inspect(method)}`);
569
+ e.code = 'ERR_INVALID_ARG_VALUE';
570
+ throw e;
422
571
  }
423
572
  assertWritable(this._materialize());
424
573
  this._headers[':method'] = method;
@@ -430,8 +579,9 @@ class Http2ServerRequest extends Readable {
430
579
  if (auth !== undefined) {
431
580
  return auth;
432
581
  }
433
- const host = h.host;
434
- return host === undefined ? undefined : String(host).replace(/:[\d]+$/, '');
582
+ // node's getAuthority (internal/http2/util.js:974) returns headers.host
583
+ // unchanged when :authority is absent; a port is part of that value.
584
+ return h.host;
435
585
  }
436
586
 
437
587
  get scheme() {
@@ -447,8 +597,27 @@ class Http2ServerRequest extends Readable {
447
597
  }
448
598
 
449
599
  setTimeout(msecs, callback) {
450
- if (!this._closed) {
451
- this._stream.setTimeout(msecs, callback);
600
+ if (!this._closed && !this._stream.destroyed) {
601
+ // node's setStreamTimeout (internal/stream_base_commons.js:246) returns
602
+ // the stream untouched once it is destroyed; a setTimeout after finish
603
+ // therefore arms nothing. The rest of the method mirrors its timer:
604
+ // stream timer and registers the callback as a once('timeout') listener;
605
+ // the compat request and response subscriptions (compat.js:303, :307)
606
+ // re-emit 'timeout' on both objects before that callback runs. h2lean's
607
+ // idle timer lives on the session, so re-emit here. One closure per
608
+ // setTimeout call, only on the opt-in path; the timer path itself is
609
+ // unchanged.
610
+ const req = this;
611
+ const res = this._stream._response;
612
+ this._stream.setTimeout(msecs, function onCompatTimeout() {
613
+ req.emit('timeout');
614
+ if (res !== undefined) {
615
+ res.emit('timeout');
616
+ }
617
+ if (callback !== undefined) {
618
+ callback.apply(this, arguments);
619
+ }
620
+ });
452
621
  }
453
622
  return this;
454
623
  }
@@ -504,6 +673,14 @@ function onResponseClose() {
504
673
  if (res === undefined || res._state.closed) {
505
674
  return;
506
675
  }
676
+ // node's onStreamCloseResponse (internal/http2/compat.js:446) opens with
677
+ // `if (this.headRequest !== state.headRequest) return`, and state.headRequest
678
+ // is only set by end(). A HEAD answer closed before end() therefore reports
679
+ // neither 'finish' nor 'close' on node; end() calls this handler itself once
680
+ // the flag is flipped.
681
+ if (this.headRequest !== res._state.headRequest) {
682
+ return;
683
+ }
507
684
  res._state.closed = true;
508
685
  res.writable = false;
509
686
  // node emits 'finish' and 'close' together, when the stream closes
@@ -538,7 +715,10 @@ class Http2ServerResponse extends Stream {
538
715
  finishEmitted: false,
539
716
  sendDate: true,
540
717
  statusCode: 200,
541
- headRequest: stream._reqMethod === 'HEAD'
718
+ // node's response state starts headRequest false and copies the stream's
719
+ // value in end() (compat.js:849); the stream itself closes HEAD answers
720
+ // at respond() time (Http2ServerStream.js:342-348).
721
+ headRequest: false
542
722
  };
543
723
  // A fast null-prototype map, not a { __proto__: null } literal: the
544
724
  // response's headers are written once and read once per response, and the
@@ -573,8 +753,7 @@ class Http2ServerResponse extends Stream {
573
753
  if (this._state.closed) {
574
754
  return undefined;
575
755
  }
576
- const session = this._stream.session;
577
- return session === undefined ? undefined : session._socket;
756
+ return compatSocket(this._stream);
578
757
  }
579
758
  get connection() {
580
759
  return this.socket;
@@ -779,9 +958,10 @@ class Http2ServerResponse extends Stream {
779
958
  // Http2ServerResponse has no sentHeaders, so `res.sentHeaders` is undefined
780
959
  // on both stacks.
781
960
  stream.respond(this._headers, {
782
- // a HEAD response must close the stream after the headers, and an
783
- // application that called end() before flushing also does
784
- endStream: state.ending || state.headRequest,
961
+ // node's compat [kBeginSend] passes only its ending flag here
962
+ // (internal/http2/compat.js:903): the stream closes a HEAD answer on
963
+ // its own, so no extra END_STREAM option is needed.
964
+ endStream: state.ending,
785
965
  sendDate: state.sendDate,
786
966
  waitForTrailers: true
787
967
  });
@@ -881,6 +1061,7 @@ class Http2ServerResponse extends Stream {
881
1061
  cb = encoding; encoding = 'utf8';
882
1062
  }
883
1063
  const state = this._state;
1064
+ const stream = this._stream;
884
1065
  let failure;
885
1066
  if (state.ending) {
886
1067
  failure = err('ERR_STREAM_WRITE_AFTER_END', 'write after end');
@@ -896,16 +1077,16 @@ class Http2ServerResponse extends Stream {
896
1077
  this.destroy(failure);
897
1078
  return false;
898
1079
  }
899
- if (state.headRequest) {
1080
+ if (stream.headRequest) {
900
1081
  if (typeof cb === 'function') {
901
1082
  this._tick(cb);
902
1083
  }
903
1084
  return true; // a HEAD response has no body
904
1085
  }
905
- if (!this._stream.headersSent) {
1086
+ if (!stream.headersSent) {
906
1087
  this.writeHead(state.statusCode);
907
1088
  }
908
- return this._stream.write(chunk, encoding, cb);
1089
+ return stream.write(chunk, encoding, cb);
909
1090
  }
910
1091
 
911
1092
  end(chunk, encoding, cb) {
@@ -917,15 +1098,19 @@ class Http2ServerResponse extends Stream {
917
1098
  cb = encoding; encoding = 'utf8';
918
1099
  }
919
1100
 
920
- if (state.closed || state.ending) {
1101
+ // node's end() guard (internal/http2/compat.js:838) also compares the two
1102
+ // headRequest flags: a HEAD whose stream closed before end() must still run
1103
+ // this call so the deferred finish/close can be reported.
1104
+ if ((state.closed || state.ending) && state.headRequest === stream.headRequest) {
921
1105
  if (typeof cb === 'function') {
922
1106
  this._tick(cb);
923
1107
  }
924
1108
  return this;
925
1109
  }
926
- if (chunk !== null && chunk !== undefined && !state.headRequest) {
1110
+ if (chunk !== null && chunk !== undefined && !stream.headRequest) {
927
1111
  this.write(chunk, encoding);
928
1112
  }
1113
+ state.headRequest = stream.headRequest;
929
1114
  state.ending = true;
930
1115
 
931
1116
  if (!stream.headersSent) {
@@ -967,6 +1152,13 @@ class Http2ServerResponse extends Stream {
967
1152
  // staging the frame twice. A body parked on window credit, a refused block and a
968
1153
  // HEAD-request close keep the deferred path -- the staged frame would land before
969
1154
  // the queued DATA, and the refused shape records the end without wire work.
1155
+ if (state.closed || stream.destroyed || stream.closed) {
1156
+ // node's end() calls onStreamCloseResponse itself when the stream already
1157
+ // closed (compat.js:862); the stream's close ran while the HEAD guard
1158
+ // still failed, so nothing reported finish/close until this call.
1159
+ onResponseClose.call(stream);
1160
+ return this;
1161
+ }
970
1162
  if (!recorded && stream._waitForTrailers && stream._queued === null &&
971
1163
  !stream._blockRefused) {
972
1164
  stream.endWithStagedEnd();
@@ -1007,7 +1199,7 @@ class Http2ServerResponse extends Stream {
1007
1199
  }
1008
1200
 
1009
1201
  setTimeout(msecs, callback) {
1010
- if (this._state.closed) {
1202
+ if (this._state.closed || this._stream.destroyed) {
1011
1203
  return this;
1012
1204
  }
1013
1205
  this._stream.setTimeout(msecs, callback);
@@ -550,7 +550,12 @@ class Http2SecureServer extends tls.Server {
550
550
  unknownProtocol(this, socket);
551
551
  }
552
552
  } else {
553
- socket.destroy();
553
+ // node's connectionListener (core.js) only diverts ALPN false and
554
+ // 'http/1.1'; every other negotiated protocol still becomes a session,
555
+ // and the session is announced with the server's 'session' event before
556
+ // the application's own 'secureConnection' listener runs. Destroying
557
+ // here used to drop that event for an ALPNCallback that picks 'a'.
558
+ attachSession(this, socket);
554
559
  }
555
560
  });
556
561
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.19.7",
3
+ "version": "0.19.9",
4
4
  "description": "Pure-JavaScript HTTP/2 for Node.js — a drop-in node:http2 replacement (server and client, h2c and TLS) with zero dependencies",
5
5
  "main": "index.js",
6
6
  "files": [