h2lean 0.19.2 → 0.19.4

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.
@@ -82,7 +82,7 @@
82
82
  // ERR_HTTP2_STREAM_ERROR(NGHTTP2_INTERNAL_ERROR) rather than throwing out of the call,
83
83
  // matching node's buildNgHeaderString/processRespondWithFD teardown: a bad field name
84
84
  // leaves headersSent true (node sets HEADERS_SENT before validating fields) and takes
85
- // the destroy path. An array-form headers argument passes through hdr.block as-is
85
+ // the destroy path. An array-form headers argument passes through hdr.prepare() as-is
86
86
  // instead of node's for..in over indices (which sends field names '0', '1', ...);
87
87
  // the content-length statCheck injects is only applied to object-form headers.
88
88
  // * 'finish' and writableFinished exist on the stream: 'finish' is queued on a
@@ -345,11 +345,11 @@ function fdOptions(options) {
345
345
  // node's prepareResponseHeadersObject (internal/http2/core.js): a null-prototype copy
346
346
  // of the caller's object with ':status' coerced in, so a statCheck that rewrites
347
347
  // 'content-length' lands on the copy -- which is also what sentHeaders reports,
348
- // exactly where node's kSentHeaders has it. The generated date is left to hdr.block,
349
- // whose sendDate rule is the one prepare applies too. Status validation happens here,
348
+ // exactly where node's kSentHeaders has it. The generated date is left to hdr.prepare(),
349
+ // whose sendDate rule governs the encode path too. Status validation happens here,
350
350
  // before the payload-forbidden check -- measured: ':status': 700 throws
351
351
  // ERR_HTTP2_STATUS_INVALID out of the call, and ':status': '700' is coerced to 700
352
- // first. The array form passes through untouched (hdr.block handles pairs natively);
352
+ // first. The array form passes through untouched (hdr.prepare() handles pairs natively);
353
353
  // node's for..in over an array copies the index keys into the copy and sends field
354
354
  // names '0', '1', ... instead -- the junk shape the header comment documents.
355
355
  function prepareResponseHeadersObject(headersParam) {
@@ -1140,6 +1140,18 @@ class Http2ClientSession extends EventEmitter {
1140
1140
  }
1141
1141
  }
1142
1142
 
1143
+ // The bound node checks before submitting a HEADERS block, from the same list the
1144
+ // encoder consumes. Computed separately so a refused request keeps the old
1145
+ // encode-then-refuse path and its encoder state, while an accepted one can skip the
1146
+ // per-request buffer entirely.
1147
+ _boundOfList(list) {
1148
+ let bound = 12;
1149
+ for (let i = 0; i < list.length; i += 3) {
1150
+ bound += 12 + list[i].length + list[i + 1].length;
1151
+ }
1152
+ return bound;
1153
+ }
1154
+
1143
1155
  _sendRequest(stream, list, neverList, end, hp) {
1144
1156
  // Fill the pseudo-headers the application omitted, in the canonical order, then
1145
1157
  // hand the whole list to HPACK. node completes :path to '/', :scheme and
@@ -1177,6 +1189,16 @@ class Http2ClientSession extends EventEmitter {
1177
1189
  neverList !== null && neverList.has(':authority'));
1178
1190
  }
1179
1191
  orderPseudo(list); // in place: `list` is built by _addField for this request only
1192
+ bound = this._boundOfList(list);
1193
+ if (bound + PRIORITY_SPECLEN <= this._maxSendBlock) {
1194
+ // Accepted: encode straight into the session's staging buffer -- no
1195
+ // per-request block allocation and no block copy. The rare refusal below
1196
+ // keeps the old path, so the encoder advances there exactly as it did before.
1197
+ stream._sid = stream.id;
1198
+ this._writeRequestBlockAt(stream.id, list, end, hp);
1199
+ this._afterRequestHeaders(stream);
1200
+ return;
1201
+ }
1180
1202
  block = this._encodeRequest(list);
1181
1203
  bound = sentBound;
1182
1204
  if (hp !== undefined && hp !== null && typeof hp === 'object') {
@@ -1190,9 +1212,13 @@ class Http2ClientSession extends EventEmitter {
1190
1212
  // what finishes the Duplex.
1191
1213
  return;
1192
1214
  }
1193
- // HEADERS is now queued; release any body the application wrote before the
1194
- // socket connected (or before this queued request was framed). The DATA frames
1195
- // land in _out behind the HEADERS, so the wire order stays HEADERS -> DATA.
1215
+ this._afterRequestHeaders(stream);
1216
+ }
1217
+
1218
+ // HEADERS is now queued; release any body the application wrote before the socket
1219
+ // connected (or before this queued request was framed). The DATA frames land in _out
1220
+ // behind the HEADERS, so the wire order stays HEADERS -> DATA.
1221
+ _afterRequestHeaders(stream) {
1196
1222
  stream._headersSent = true;
1197
1223
  stream.headersSent = true;
1198
1224
  if (stream._pending !== null || stream._finalCb !== null) {
@@ -1204,10 +1230,10 @@ class Http2ClientSession extends EventEmitter {
1204
1230
  const enc = this._encoder;
1205
1231
  // The dynamic-table-size announcement has to precede the block it applies to, and its
1206
1232
  // length is not known before the block is written: the field lines are what change the
1207
- // table, and the announcement reports where the table ended up. So the take happens
1208
- // first and its octets are copied into the headroom of the same buffer the block is
1209
- // encoded into -- never into a second one.
1210
- const update = enc.takeSizeUpdate();
1233
+ // table, and the announcement reports where the table ended up. Five octets are
1234
+ // reserved at the front of the one buffer this block is encoded into, and
1235
+ // takeSizeUpdateInto() writes the announcement there and returns the exact offset
1236
+ // the field lines start at -- no intermediate Buffer and no copy.
1211
1237
  let cap = 0;
1212
1238
  // nghttp2's outbound estimate, accumulated in the pass that already sizes the
1213
1239
  // scratch -- the same formula and the same string-length-not-octets rule
@@ -1220,29 +1246,76 @@ class Http2ClientSession extends EventEmitter {
1220
1246
  bound += 12 + list[i].length + list[i + 1].length;
1221
1247
  }
1222
1248
  sentBound = bound;
1223
- // Without a size update the block IS the scratch: _sendHeaders runs before any later
1249
+ // Without a size update the block IS the buffer: _sendHeaders runs before any later
1224
1250
  // encode can rewrite it, and _frame(owned=false) puts a stable copy in the batch.
1225
1251
  // With one, the old form was Buffer.concat([update, block]) -- a second allocation,
1226
- // a second copy of the whole block and a temporary array per request. Reserving the
1227
- // update's length up front costs one memcpy of the update itself
1228
- // (OPTIMIZATION.md item 14).
1229
- // The headroom exists on this branch only, and the returned view then starts past
1230
- // the front of its buffer -- which every consumer here reads as
1252
+ // a second copy of the whole block and a temporary array per request. The announcement
1253
+ // now goes straight into the reserved headroom (OPTIMIZATION.md item 14). The returned
1254
+ // view then starts past the front of its buffer -- every consumer here reads
1231
1255
  // .length/.copy/write(), all of which honour byteOffset.
1232
- const ul = update === null ? 0 : update.length;
1233
- const buf = Buffer.allocUnsafe(ul + cap);
1256
+ const buf = Buffer.allocUnsafe(5 + cap);
1234
1257
  enc.unsettled = false;
1235
- let off = ul;
1258
+ let off = enc.takeSizeUpdateInto(buf, 0);
1236
1259
  for (let i = 0; i < list.length; i += 3) {
1237
1260
  off = enc.write(buf, off, list[i], list[i + 1], list[i + 2]);
1238
1261
  }
1239
- if (ul === 0) {
1240
- return buf.subarray(0, off);
1241
- }
1242
- f.copyInto(buf, 0, update, 0, update.length);
1243
1262
  return buf.subarray(0, off);
1244
1263
  }
1245
1264
 
1265
+ // The accepted-request path: the size update is consumed into the destination, every
1266
+ // field line is encoded there, and the 9-octet frame headers are inserted in place
1267
+ // from the last CONTINUATION backwards -- the same shape as the server's
1268
+ // _writeBlockAt (OPTIMIZATION.md items 14, 68). The cache gets one owned snapshot;
1269
+ // later sightings of the same object replay it through _sendHeaders as before.
1270
+ _writeRequestBlockAt(sid, list, end, hp) {
1271
+ const enc = this._encoder;
1272
+ let cap = 5; // room for the largest 5-bit-prefix size update
1273
+ let bound = 12;
1274
+ for (let i = 0; i < list.length; i += 3) {
1275
+ cap += Encoder.maxBytesOf(list[i], list[i + 1]);
1276
+ bound += 12 + list[i].length + list[i + 1].length;
1277
+ }
1278
+ sentBound = bound;
1279
+ const max = this.remoteSettings.maxFrameSize;
1280
+ const frames = Math.max(1, Math.ceil(cap / max));
1281
+ this._need(HEADER_LEN + cap + HEADER_LEN * (frames - 1));
1282
+ const dst = this._stage;
1283
+ const off = this._stageLen;
1284
+ const payloadOff = off + HEADER_LEN;
1285
+ let o = enc.takeSizeUpdateInto(dst, payloadOff);
1286
+ enc.unsettled = false;
1287
+ for (let i = 0; i < list.length; i += 3) {
1288
+ o = enc.write(dst, o, list[i], list[i + 1], list[i + 2]);
1289
+ }
1290
+ const n = o - payloadOff;
1291
+ const used = Math.max(1, Math.ceil(n / max));
1292
+ const es = end ? F_END_STREAM : 0;
1293
+ if (used === 1) {
1294
+ writeHeader(dst, off, n, HEADERS, F_END_HEADERS | es, sid);
1295
+ } else {
1296
+ for (let i = used - 1; i >= 1; i--) {
1297
+ const src = payloadOff + i * max;
1298
+ dst.copyWithin(src + i * HEADER_LEN, src, Math.min(o, src + max));
1299
+ }
1300
+ for (let i = 0; i < used; i++) {
1301
+ const take = Math.min(n - i * max, max);
1302
+ const flags = i === 0 ? es : (i === used - 1 ? F_END_HEADERS : 0);
1303
+ writeHeader(dst, off + i * (HEADER_LEN + max), take,
1304
+ i === 0 ? HEADERS : CONTINUATION, flags, sid);
1305
+ }
1306
+ }
1307
+ const total = HEADER_LEN * used + n;
1308
+ this._stageLen = off + total;
1309
+ this._outLen += total;
1310
+ if (hp !== undefined && hp !== null && typeof hp === 'object') {
1311
+ this._blocks.set(hp, { epoch: enc.epoch,
1312
+ block: Buffer.from(dst.subarray(payloadOff, o)), bound });
1313
+ }
1314
+ if (!this._inBatch) {
1315
+ this._schedule();
1316
+ }
1317
+ }
1318
+
1246
1319
  // Returns true when the block was refused. `opening` says whether this HEADERS is the
1247
1320
  // one that opens the stream on the wire, which is what decides the refusal's shape:
1248
1321
  // nghttp2's prep-error path closes a stream-opening request HEADERS itself with
package/lib/headers.js CHANGED
@@ -44,11 +44,13 @@ function nullProto() {
44
44
  }
45
45
 
46
46
  // Encoded bytes for one response, reused between calls. The encoder that fills it
47
- // belongs to the session (lib/session), because a dynamic table is per-connection
48
- // state, so nothing on this path is shared between sessions.
49
- // A response block lives for microseconds: _frame() copies it into the staging buffer
50
- // of the outbound queue, so the queue never holds a view of this scratch. See block()
51
- // before holding on to the returned view across another call.
47
+ // belongs to the session (lib/server/Http2ServerSession.js), because a dynamic table
48
+ // is per-connection state, so nothing on this path is shared between sessions.
49
+ // The server path does not touch this buffer: prepare()/writePrepared() write straight
50
+ // into the session's staging buffer (OPTIMIZATION.md item 68), including the refused
51
+ // PUSH_PROMISE response, which is parsed but never encoded. block() survives for the
52
+ // tests and microbenches that need a standalone block and exercise the block cache. A
53
+ // caller must finish with that view before the next block() call rewrites the scratch.
52
54
  let scratch = Buffer.allocUnsafe(4096);
53
55
 
54
56
  const isToken = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
@@ -220,13 +222,6 @@ let singlesSeen = [];
220
222
  const CONNECTION_SPECIFIC = new Set(['connection', 'keep-alive', 'proxy-connection',
221
223
  'transfer-encoding', 'upgrade']);
222
224
 
223
- // Whether a field value carries a character that may not appear in one. The server's
224
- // inbound path asks the same question (lib/server/Http2ServerSession.js) and answers it the way nghttp2
225
- // does: the field is ignored, the stream lives.
226
- function hasBadValue(value) {
227
- return badValue.test(value);
228
- }
229
-
230
225
  // The names of the field lines that arrived as never-indexed HPACK literals,
231
226
  // one entry per delivered line, duplicates and arrival order kept. node hangs
232
227
  // this under its `sensitiveHeaders` symbol on every inbound header object --
@@ -548,7 +543,6 @@ function block(headers, opts, session) {
548
543
  }
549
544
  }
550
545
 
551
- const update = enc.takeSizeUpdate();
552
546
  const parsed = parse(headers,
553
547
  { trailer: !!(opts && opts.trailer), sendDate, info: !!(opts && opts.info),
554
548
  strict: session._strictSingle });
@@ -566,13 +560,17 @@ function block(headers, opts, session) {
566
560
  const epoch = enc.epoch;
567
561
  // The announcement goes in front of the block, in the same buffer: the old form was
568
562
  // Buffer.concat([update, out]) -- a second allocation, a copy of the whole block and a
569
- // temporary array, on the one path where the peer changed the table size. The client
570
- // does the same thing in its own _encodeRequest (lib/client/Http2ClientSession.js).
571
- const at = update === null ? 0 : update.length;
563
+ // temporary array, on the one path where the peer changed the table size. Reserve the
564
+ // largest 5-bit-prefix announcement before writing so encodeAt() cannot move the
565
+ // scratch under it, then let takeSizeUpdateInto() consume the pending change and use
566
+ // its exact length as the block's start offset. The client does the same in its own
567
+ // _encodeRequest (lib/client/Http2ClientSession.js).
568
+ const need = capOf(parsed, 5);
569
+ if (scratch.length < need) {
570
+ scratch = Buffer.allocUnsafe(need);
571
+ }
572
+ const at = enc.takeSizeUpdateInto(scratch, 0);
572
573
  const end = encodeAt(parsed, enc, at);
573
- if (at !== 0) {
574
- copyInto(scratch, 0, update, 0, update.length);
575
- }
576
574
  if (cacheable && enc.epoch === epoch && !enc.unsettled) {
577
575
  // a cached block has to outlive the scratch, so only the cached path copies --
578
576
  // allocUnsafe, not Buffer.from(subarray): at the sizes a response block has the
@@ -697,8 +695,8 @@ function prepare(headers, opts, session) {
697
695
  sent.status = parsed.status;
698
696
  sent.date = parsed.genDate;
699
697
  // The size update is NOT consumed here: writePrepared() writes its octets into the
700
- // destination itself. Reserve the maximum the 5-bit prefix can need (the same
701
- // bound takeSizeUpdate() allocates) so the encoder has room before a byte is written.
698
+ // destination itself. Reserve the maximum the 5-bit prefix can need (the room
699
+ // takeSizeUpdateInto() checks) so the encoder has room before a byte is written.
702
700
  const at = enc.pendingSize === null ? 0 : 5;
703
701
  let bound = 12;
704
702
  let cap = 16 + at;
@@ -719,7 +717,7 @@ function prepare(headers, opts, session) {
719
717
 
720
718
  function writePrepared(prep, session, dst, off) {
721
719
  const enc = session._encoder;
722
- // Same octets as takeSizeUpdate(), written into the caller's buffer: no 5-octet
720
+ // The announcement goes straight into the caller's buffer: no standalone 5-octet
723
721
  // Buffer and no subarray. The encoder consumes the pending update here, so the
724
722
  // announcement cannot be repeated by a later block.
725
723
  const at = enc.takeSizeUpdateInto(dst, off) - off;
@@ -875,5 +873,5 @@ function requestView(src, scheme, authority) {
875
873
 
876
874
  module.exports = { block, encode, parse, prepare, writePrepared, capOf, boundOf,
877
875
  nullProto, isFieldName, trimName, lowerName,
878
- nameCacheSize, hasBadValue, neverNames, CONNECTION_SPECIFIC, KSensitiveHeaders, SINGLE_VALUE_FIELDS,
876
+ nameCacheSize, neverNames, CONNECTION_SPECIFIC, KSensitiveHeaders, SINGLE_VALUE_FIELDS,
879
877
  sent, responseView, requestView };
package/lib/hpack.js CHANGED
@@ -1226,21 +1226,9 @@ class Encoder {
1226
1226
  } // the indices the caches name just shifted
1227
1227
  }
1228
1228
 
1229
- // The size update octets for the next field block, or null. Consumed here so a block
1230
- // never announces the same change twice.
1231
- takeSizeUpdate() {
1232
- const n = this.pendingSize;
1233
- if (n === null) {
1234
- return null;
1235
- }
1236
- this.pendingSize = null;
1237
- const b = Buffer.allocUnsafe(5);
1238
- return b.subarray(0, writeInt(b, 0, n, 5, 0x20));
1239
- }
1240
-
1241
- // The size update written straight into the caller's destination. Same octets as
1242
- // takeSizeUpdate(), but the direct-write path has no intermediate 5-octet Buffer
1243
- // and no subarray to hand to the staging buffer.
1229
+ // The size update written straight into the caller's destination, consumed here so
1230
+ // a block never announces the same change twice. No intermediate 5-octet Buffer and
1231
+ // no subarray to hand to the staging buffer. Returns the offset after the octets.
1244
1232
  takeSizeUpdateInto(dst, off) {
1245
1233
  const n = this.pendingSize;
1246
1234
  if (n === null) {
@@ -74,7 +74,7 @@
74
74
  // ERR_HTTP2_STREAM_ERROR(NGHTTP2_INTERNAL_ERROR) rather than throwing out of the call,
75
75
  // matching node's buildNgHeaderString/processRespondWithFD teardown: a bad field name
76
76
  // leaves headersSent true (node sets HEADERS_SENT before validating fields) and takes
77
- // the destroy path. An array-form headers argument passes through hdr.block as-is
77
+ // the destroy path. An array-form headers argument passes through hdr.prepare() as-is
78
78
  // instead of node's for..in over indices (which sends field names '0', '1', ...);
79
79
  // the content-length statCheck injects is only applied to object-form headers.
80
80
  // * 'finish' and writableFinished exist on the stream: 'finish' is queued on a
@@ -354,13 +354,15 @@ class Http2ServerStream extends Http2Stream {
354
354
  // internal/http2/util.js) -- there is no options.sensitiveHeaders for node to ignore.
355
355
  // A refused PUSH_PROMISE closed the promised stream at submit time: node never
356
356
  // submits its response block, so sending it here would put HEADERS on a stream
357
- // the peer never opened (GOAWAY(PROTOCOL_ERROR) there). Keep building the block
358
- // -- it sets sentHeaders and advances the encoder as block() does -- but do not
359
- // write it: sendHeadersAt() writes straight into the session's stage and cannot
360
- // be called and then discarded.
357
+ // the peer never opened (GOAWAY(PROTOCOL_ERROR) there). Keep parsing the block so
358
+ // sentHeaders still reports this response, but do not encode or write it: a live
359
+ // node probe measured the parent's next HEADERS byte-identical to a session that
360
+ // never built the discarded block, so our encoder must not advance either, and
361
+ // sendHeadersAt() writes straight into the session's stage where it cannot be
362
+ // called and then discarded.
361
363
  let refused = this._blockRefused;
362
364
  if (refused) {
363
- hdr.block(headers, { sendDate }, this.session);
365
+ hdr.prepare(headers, { sendDate }, this.session);
364
366
  } else {
365
367
  refused = this.session.sendHeadersAt(this.id, headers, { sendDate },
366
368
  opts.endStream === true || head || this._endQueued);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.19.2",
3
+ "version": "0.19.4",
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": [