-
-
Notifications
You must be signed in to change notification settings - Fork 878
Expand file tree
/
Copy pathclient-h2.js
More file actions
1976 lines (1621 loc) · 55.4 KB
/
Copy pathclient-h2.js
File metadata and controls
1976 lines (1621 loc) · 55.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
const assert = require('node:assert')
const { pipeline } = require('node:stream')
const util = require('../core/util.js')
const {
RequestContentLengthMismatchError,
RequestAbortedError,
SocketError,
InformationalError,
InvalidArgumentError,
HeadersTimeoutError,
BodyTimeoutError,
ResponseExceededMaxSizeError
} = require('../core/errors.js')
const {
kUrl,
kReset,
kClient,
kRunning,
kPending,
kQueue,
kPendingIdx,
kRunningIdx,
kError,
kSocket,
kStrictContentLength,
kOnError,
kMaxConcurrentStreams,
kHTTP2Session,
kHostAuthority,
kResume,
kSize,
kHTTPContext,
kClosed,
kKeepAliveDefaultTimeout,
kHeadersTimeout,
kBodyTimeout,
kEnableConnectProtocol,
kRemoteSettings,
kHTTP2Stream,
kHTTP2SessionState,
kHTTP2Options,
kMaxResponseSize,
kMaxRequests,
kCounter
} = require('../core/symbols.js')
const { channels } = require('../core/diagnostics.js')
const kOpenStreams = Symbol('open streams')
const kRequestStreamId = Symbol('request stream id')
const kRequestStream = Symbol('request stream')
const kRequestStreamCleanup = Symbol('request stream cleanup')
const kRequestStreamState = Symbol('request stream state')
const kReceivedGoAway = Symbol('received goaway')
const kGoAwayReplayAttempts = Symbol('goaway replay attempts')
const kRefusedStreamRetry = Symbol('refused stream retry')
const kRetiringSession = Symbol('retiring session')
// RFC 9113 section 8.7: a client SHOULD NOT automatically retry a request more
// than once. Without a budget a peer that keeps refusing turns one request into
// an unbounded connect/refuse/reconnect loop that never settles and starves the
// event loop.
const MAX_GOAWAY_REPLAY_ATTEMPTS = 1
let extractBody
/** @type {import('http2')} */
let http2
try {
http2 = require('node:http2')
} catch {
// @ts-ignore
http2 = { constants: {} }
}
const {
constants: {
HTTP2_HEADER_AUTHORITY,
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_SCHEME,
HTTP2_HEADER_CONTENT_LENGTH,
HTTP2_HEADER_EXPECT,
HTTP2_HEADER_STATUS,
HTTP2_HEADER_PROTOCOL,
NGHTTP2_NO_ERROR,
NGHTTP2_REFUSED_STREAM
}
} = http2
function getGoAwayError (session, errorCode) {
return session[kError] ||
(errorCode === NGHTTP2_NO_ERROR
? new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`)
: new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(session[kSocket])))
}
function resetHttp2Session (session, err) {
const client = session[kClient]
const socket = session[kSocket]
clearRetiredSessionTimeout(session)
if (client[kHTTP2Session] === session) {
client[kSocket] = null
client[kHTTPContext] = null
client[kHTTP2Session] = null
}
if (socket != null && socket[kError] == null) {
socket[kError] = err
}
if (!session.closed && !session.destroyed) {
try {
session.destroy(err)
} catch {}
}
util.destroy(socket, err)
}
function getGoAwayPendingIdx (client, lastStreamID) {
const maxAcceptedStreamID = Number.isInteger(lastStreamID) ? lastStreamID : Number.MAX_SAFE_INTEGER
for (let i = client[kRunningIdx]; i < client[kPendingIdx]; i++) {
const request = client[kQueue][i]
if (request == null) {
continue
}
if (typeof request[kRequestStreamId] !== 'number' || request[kRequestStreamId] > maxAcceptedStreamID) {
return i
}
}
return client[kPendingIdx]
}
function detachRequestFromStream (request) {
request[kRequestStreamId] = null
request[kRequestStream] = null
request[kRequestStreamCleanup] = null
}
function bindRequestToStream (request, stream, cleanup) {
const previousCleanup = request[kRequestStreamCleanup]
const previousStream = request[kRequestStream]
detachRequestFromStream(request)
previousCleanup?.(previousStream)
request[kRequestStreamId] = stream.id
request[kRequestStream] = stream
request[kRequestStreamCleanup] = cleanup
}
function clearRequestStream (request) {
const cleanup = request[kRequestStreamCleanup]
const stream = request[kRequestStream]
detachRequestFromStream(request)
cleanup?.(stream)
}
function requeueUnsentRequest (client, request) {
client[kQueue].splice(client[kPendingIdx] + 1, 0, request)
}
function completeRequest (client, request, resetPendingIdx = false) {
const queue = client[kQueue]
const runningIdx = client[kRunningIdx]
// In-order completion: clear the request and advance without splicing.
// The client's resume loop compacts cleared slots once the index grows.
if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request) {
queue[runningIdx] = null
client[kRunningIdx] = runningIdx + 1
return
}
const index = queue.indexOf(request, runningIdx)
if (index === -1 || index >= client[kPendingIdx]) {
return
}
queue.splice(index, 1)
client[kPendingIdx]--
if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
client[kPendingIdx] = client[kRunningIdx]
}
}
function canReplayRequest (request) {
const { body } = request
return body == null || util.isBuffer(body) || util.isBlobLike(body)
}
// Count a GOAWAY refusal against the request's replay budget. A peer that
// refuses every connection must eventually surface an error to the caller
// rather than being retried forever. Kept separate from canReplayRequest so
// that the REFUSED_STREAM retry, which has its own single-attempt limit, does
// not consume this budget just by asking whether the body can be replayed.
function registerGoAwayRefusal (request) {
const attempts = (request[kGoAwayReplayAttempts] ?? 0) + 1
request[kGoAwayReplayAttempts] = attempts
return attempts <= MAX_GOAWAY_REPLAY_ATTEMPTS
}
function closeStream (stream, code = NGHTTP2_REFUSED_STREAM) {
if (stream != null && !stream.destroyed && !stream.closed) {
try {
stream.close(code)
} catch {}
}
}
function detachRequestStreamForClose (request) {
const stream = request[kRequestStream]
clearRequestStream(request)
severRequestStream(stream)
return stream
}
// Unbind a stream from its request for good. releaseRequestStream() alone
// leaves the 'close' listener attached and kRequestStreamState populated, so a
// stream abandoned here would still run completeRequestStream() later — and
// splice out the request that has since been requeued onto another session.
function severRequestStream (stream) {
if (stream == null || stream[kRequestStreamState] == null) {
return
}
stream[kRequestStreamState] = null
stream.off('close', completeRequestStream)
// Upgrade streams use their own close cleanup, which would otherwise release
// the session a second time after the stream has been severed for GOAWAY.
stream.off('close', onUpgradeStreamClose)
if (stream[kHTTP2Session] != null) {
closeStreamSession(stream)
}
if (!stream.destroyed && !stream.closed) {
stream.once('error', noop)
}
}
function connectH2 (client, socket) {
client[kSocket] = socket
const http2InitialWindowSize = client[kHTTP2Options].sessionOptions?.initialWindowSize
const http2ConnectionWindowSize = client[kHTTP2Options].connectionWindowSize
const session = http2.connect(client[kUrl], {
createConnection: () => socket,
peerMaxConcurrentStreams: client[kHTTP2Options].maxConcurrentStreams,
settings: {
// TODO(metcoder95): add support for PUSH
enablePush: false,
...(http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null)
}
})
client[kSocket] = socket
session[kOpenStreams] = 0
session[kClient] = client
session[kSocket] = socket
session[kHTTP2SessionState] = {
idleTimeout: null,
// Armed while the peer advertises MAX_CONCURRENT_STREAMS = 0 and we have
// work that cannot start. See setNoStreamsTimeout.
noStreamsTimeout: null,
// Set once the session has opened maxRequestsPerClient streams. A retired
// session never accepts another stream; it drains and is then torn down.
// See trackH2Stream.
retired: false,
// Bounds how long a retired session may wait for its accepted streams to
// close before they are destroyed so queued work can reconnect.
retiredSessionTimeout: null,
// Number of streams counted against maxRequestsPerClient that have not
// physically closed yet. Only maintained when the limit is enabled.
countedStreams: 0,
// Set when closeRetiredH2Session has already emitted 'disconnect' and
// resumed the queue, so that the trailing socket close does not do it
// again. See onHttp2SocketClose.
disconnectAnnounced: false,
// Sockets start out ref'd. Session ref/unref proxies to the socket, so a
// single cached flag lets us skip redundant uv ref/unref calls, provided
// every ref/unref of the session or its socket goes through
// refH2Session/unrefH2Session.
refed: true,
ping: {
interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref()
}
}
session[kReceivedGoAway] = false
// We set it to true by default in a best-effort; however once connected to an H2 server
// we will check if extended CONNECT protocol is supported or not
// and set this value accordingly.
session[kEnableConnectProtocol] = false
// States whether or not we have received the remote settings from the server
session[kRemoteSettings] = false
// Apply connection-level flow control once connected (if supported).
if (http2ConnectionWindowSize) {
util.addListener(session, 'connect', applyConnectionWindowSize.bind(session, http2ConnectionWindowSize))
}
util.addListener(session, 'error', onHttp2SessionError)
util.addListener(session, 'frameError', onHttp2FrameError)
util.addListener(session, 'goaway', onHttp2SessionGoAway)
util.addListener(session, 'close', onHttp2SessionClose)
util.addListener(session, 'remoteSettings', onHttp2RemoteSettings)
// TODO (@metcoder95): implement SETTINGS support
// util.addListener(session, 'localSettings', onHttp2RemoteSettings)
unrefH2Session(session)
client[kHTTP2Session] = session
socket[kHTTP2Session] = session
util.addListener(socket, 'error', onHttp2SocketError)
util.addListener(socket, 'end', onHttp2SocketEnd)
util.addListener(socket, 'close', onHttp2SocketClose)
socket[kClosed] = false
socket.on('close', onSocketClose)
return {
version: 'h2',
defaultPipelining: Infinity,
/**
* @param {import('../core/request.js')} request
* @returns {boolean}
*/
write (request) {
return writeH2(client, request)
},
/**
* @returns {void}
*/
resume () {
resumeH2(client)
},
/**
* @param {Error | null} err
* @param {() => void} callback
*/
destroy (err, callback) {
if (socket[kClosed]) {
queueMicrotask(callback)
} else {
socket.destroy(err).on('close', callback)
}
},
/**
* @type {boolean}
*/
get destroyed () {
return socket.destroyed
},
/**
* @param {import('../core/request.js')} request
* @returns {boolean}
*/
busy (request) {
// A session that has reached maxRequestsPerClient is draining: it must
// not receive another stream, so queued work waits here until the session
// is torn down and a fresh one replaces it.
if (session[kHTTP2SessionState].retired === true) {
return true
}
if (session[kRemoteSettings] === false && client[kRunning] > 0) {
return true
}
if (client[kRunning] >= client[kMaxConcurrentStreams]) {
return true
}
if (request != null) {
if (client[kRunning] > 0) {
// We are already processing requests
// Unlike HTTP/1.1 pipelining, HTTP/2 multiplexes requests on
// independent streams, so non-idempotent requests can be dispatched
// concurrently. Retry eligibility is handled by stream/session error
// handling instead of by serializing all non-idempotent requests.
// Don't dispatch an upgrade until all preceding requests have completed.
// Possibly, we do not have remote settings confirmed yet.
if ((request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false) return true
} else {
return (request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false
}
}
return false
}
}
}
// Session ref/unref proxies to the underlying socket, so refH2Session and
// unrefH2Session cover both and can skip the call when the cached ref state
// already matches.
function refH2Session (session) {
const state = session[kHTTP2SessionState]
if (state.refed === false) {
state.refed = true
session.ref()
}
}
function unrefH2Session (session) {
const state = session[kHTTP2SessionState]
if (state.refed === true) {
state.refed = false
session.unref()
}
}
function resumeH2 (client) {
const socket = client[kSocket]
const session = client[kHTTP2Session]
if (socket?.destroyed === false) {
if (session[kHTTP2SessionState].retired === true) {
// A retired session must not be unref'ed or given an idle timeout: the
// streams it already accepted may still be uploading. Teardown happens
// in onCountedStreamClose once the last of them is physically closed.
return
}
// After an upgrade the queue is empty but its stream is still in use, so never unref while a stream is open.
if (session[kOpenStreams] === 0 && (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0)) {
unrefH2Session(session)
} else {
refH2Session(session)
}
if (client[kSize] === 0 && session[kOpenStreams] === 0) {
setHttp2IdleTimeout(session)
} else {
clearHttp2IdleTimeout(session)
}
if (client[kMaxConcurrentStreams] === 0 && client[kRunning] === 0 && client[kPending] > 0) {
setNoStreamsTimeout(session)
} else {
clearNoStreamsTimeout(session)
}
}
}
function clearNoStreamsTimeout (session) {
const state = session[kHTTP2SessionState]
if (state?.noStreamsTimeout != null) {
clearTimeout(state.noStreamsTimeout)
state.noStreamsTimeout = null
}
}
function clearRetiredSessionTimeout (session) {
const state = session[kHTTP2SessionState]
if (state?.retiredSessionTimeout != null) {
clearTimeout(state.retiredSessionTimeout)
state.retiredSessionTimeout = null
}
}
function setRetiredSessionTimeout (session) {
const client = session[kClient]
const state = session[kHTTP2SessionState]
const timeout = client[kHeadersTimeout]
if (!timeout || state.retiredSessionTimeout != null) {
return
}
state.retiredSessionTimeout = setTimeout(onRetiredSessionTimeout, timeout, session).unref()
}
function onRetiredSessionTimeout (session) {
const client = session[kClient]
const state = session[kHTTP2SessionState]
state.retiredSessionTimeout = null
if (
client[kHTTP2Session] !== session ||
state.retired !== true ||
state.countedStreams === 0 ||
session.closed ||
session.destroyed
) {
return
}
closeRetiredH2Session(
session,
new InformationalError(
`HTTP/2: retired session did not drain within ${client[kHeadersTimeout]}`
)
)
}
// A peer is allowed to advertise SETTINGS_MAX_CONCURRENT_STREAMS = 0 to refuse
// new streams (RFC 9113 §6.5.2), and is expected to raise it again later. Until
// it does, busy() reports the client as permanently busy and queued requests
// cannot open a stream — which means no per-stream timeout covers them, and no
// reconnect can happen either, so the SETTINGS frame that would lift the limit
// can never arrive. Give the peer headersTimeout to start honouring requests
// before failing them; a request that cannot even be sent has missed the same
// deadline as one whose headers never arrive.
function setNoStreamsTimeout (session) {
const client = session[kClient]
const state = session[kHTTP2SessionState]
const timeout = client[kHeadersTimeout]
if (!timeout || state.noStreamsTimeout != null) {
return
}
state.noStreamsTimeout = setTimeout(onNoStreamsTimeout, timeout, session).unref()
}
function onNoStreamsTimeout (session) {
const client = session[kClient]
const state = session[kHTTP2SessionState]
state.noStreamsTimeout = null
if (
client[kHTTP2Session] !== session ||
client[kMaxConcurrentStreams] !== 0 ||
client[kRunning] !== 0 ||
client[kPending] === 0
) {
return
}
const err = new HeadersTimeoutError(
`HTTP/2: server did not accept a new stream within ${client[kHeadersTimeout]}`
)
const requests = client[kQueue].splice(client[kPendingIdx])
for (let i = 0; i < requests.length; i++) {
if (requests[i] != null) {
util.errorRequest(client, requests[i], err)
}
}
// Drop the unusable session so the next request gets a fresh connection,
// whose SETTINGS may well allow streams again.
session[kError] = err
resetHttp2Session(session, err)
}
function clearHttp2IdleTimeout (session) {
const state = session[kHTTP2SessionState]
if (state?.idleTimeout != null) {
clearTimeout(state.idleTimeout)
state.idleTimeout = null
}
}
function setHttp2IdleTimeout (session) {
const client = session[kClient]
if (client[kHTTP2Session] !== session || session.closed || session.destroyed) {
return
}
if (session[kOpenStreams] !== 0 || client[kSize] !== 0) {
clearHttp2IdleTimeout(session)
return
}
const state = session[kHTTP2SessionState]
if (state.idleTimeout == null) {
state.idleTimeout = setTimeout(onHttp2SessionIdleTimeout, client[kKeepAliveDefaultTimeout], session).unref()
}
}
function onHttp2SessionIdleTimeout (session) {
const client = session[kClient]
const socket = session[kSocket]
const state = session[kHTTP2SessionState]
state.idleTimeout = null
if (client[kHTTP2Session] !== session || session[kOpenStreams] !== 0 || client[kSize] !== 0 || session.closed || session.destroyed) {
return
}
const err = new InformationalError('socket idle timeout')
socket[kError] = err
util.destroy(socket, err)
}
// Called once for every stream that session.request() successfully opened.
// Besides the shared bookkeeping (an open stream cancels the idle timeout and
// keeps the session alive) this is where maxRequestsPerClient is enforced: for
// HTTP/2 one request is one opened stream, so a stream that never made it past
// session.request() must not consume the budget.
function trackH2Stream (session, stream) {
clearHttp2IdleTimeout(session)
++session[kOpenStreams]
const maxRequests = session[kClient][kMaxRequests]
// `null`, `undefined` and `0` all disable the limit, as in HTTP/1.1.
if (!maxRequests) {
return
}
// kOpenStreams is released as soon as the response is complete, which for
// HTTP/2 can happen while the request body is still being uploaded. Track the
// physical stream separately so that retiring the session cannot truncate
// that upload.
session[kHTTP2SessionState].countedStreams += 1
stream[kRetiringSession] = session
stream.once('close', onCountedStreamClose)
const socket = session[kSocket]
const counter = (socket[kCounter] ?? 0) + 1
socket[kCounter] = counter
// `>=` mirrors client-h1.js: the stream that reaches the limit is served,
// the next one is not.
if (counter >= maxRequests) {
// Retire synchronously so that a resume loop dispatching several requests
// in one pass cannot slip stream N+1 onto this session: busy() reads the
// flag before every write. Teardown is left to onCountedStreamClose, which
// runs once every stream this session accepted has physically closed.
session[kHTTP2SessionState].retired = true
setRetiredSessionTimeout(session)
}
}
function onCountedStreamClose () {
const session = this[kRetiringSession]
if (session == null) {
return
}
this[kRetiringSession] = null
const state = session[kHTTP2SessionState]
state.countedStreams -= 1
if (state.retired === true && state.countedStreams === 0) {
closeRetiredH2Session(session)
}
}
// Tearing the session down is deliberately deferred until it has drained.
// Doing it in the same tick as session.request() makes nghttp2 refuse the very
// stream that triggered retirement, and a locally initiated graceful
// session.close() can leave the socket half-open indefinitely when the peer
// keeps its side open (for example when it sent a GOAWAY of its own). Once no
// stream is left there is nothing to be graceful about, so reuse the standard
// reset path. The error is informational so queued requests remain available
// to replay on a fresh session, including when the drain deadline expires.
function closeRetiredH2Session (
session,
err = new InformationalError('HTTP/2: session retired after reaching maxRequestsPerClient')
) {
clearHttp2IdleTimeout(session)
clearNoStreamsTimeout(session)
clearRetiredSessionTimeout(session)
if (session.destroyed) {
return
}
const client = session[kClient]
const state = session[kHTTP2SessionState]
// Only the attached session owns the client's connection state, so only it
// may announce the disconnect. The flag tells onHttp2SocketClose that this
// has already been taken care of; it is deliberately not `state.retired`,
// because a retired session can also be torn down by the peer, and that path
// still needs onHttp2SocketClose to flush the client state.
const announce = client[kHTTP2Session] === session
state.disconnectAnnounced = announce
session[kError] = err
resetHttp2Session(session, err)
if (announce) {
client.emit('disconnect', client[kUrl], [client], err)
client[kResume]()
}
}
function applyConnectionWindowSize (connectionWindowSize) {
try {
if (typeof this.setLocalWindowSize === 'function') {
this.setLocalWindowSize(connectionWindowSize)
}
} catch {
// Best-effort only.
}
}
function onHttp2RemoteSettings (settings) {
// Fallbacks are a safe bet, remote setting will always override
this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams]
/**
* From RFC-8441
* A sender MUST NOT send a SETTINGS_ENABLE_CONNECT_PROTOCOL parameter
* with the value of 0 after previously sending a value of 1.
*/
// Note: Cannot be tested in Node, it does not supports disabling the extended CONNECT protocol once enabled
if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) {
const err = new InformationalError('HTTP/2: Server disabled extended CONNECT protocol against RFC-8441')
this[kSocket][kError] = err
this[kClient][kOnError](err)
return
}
this[kEnableConnectProtocol] = settings.enableConnectProtocol ?? this[kEnableConnectProtocol]
this[kRemoteSettings] = true
this[kClient][kResume]()
}
function onHttp2SendPing (session) {
const state = session[kHTTP2SessionState]
if ((session.closed || session.destroyed) && state.ping.interval != null) {
clearInterval(state.ping.interval)
state.ping.interval = null
return
}
// If no ping sent, do nothing
session.ping(onPing.bind(session))
function onPing (err, duration) {
const client = this[kClient]
const socket = this[kSocket]
if (err != null) {
const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`)
socket[kError] = error
client[kOnError](error)
} else {
client.emit('ping', duration)
}
}
}
function onHttp2SessionError (err) {
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
this[kSocket][kError] = err
if (this[kReceivedGoAway]) {
return
}
this[kClient][kOnError](err)
}
function onHttp2FrameError (type, code, id) {
if (id === 0) {
if (this[kReceivedGoAway]) {
return
}
const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
this[kSocket][kError] = err
this[kClient][kOnError](err)
}
}
/**
* This is the root cause of #3011
* We need to handle GOAWAY frames properly, and trigger the session close
* along with the socket right away
*
* @this {import('http2').ClientHttp2Session}
* @param {number} errorCode
* @param {number} lastStreamID
*/
function onHttp2SessionGoAway (errorCode, lastStreamID) {
if (this[kReceivedGoAway]) {
return
}
this[kReceivedGoAway] = true
const err = getGoAwayError(this, errorCode)
const client = this[kClient]
const previousPendingIdx = client[kPendingIdx]
const pendingIdx = getGoAwayPendingIdx(client, lastStreamID)
const retriableRequests = []
const streamsToClose = []
// Closing one stream after GOAWAY can synchronously emit frameError on
// sibling streams. Detach all affected requests first so those errors do
// not fail requests that are about to be requeued.
for (let i = pendingIdx; i < previousPendingIdx; i++) {
const request = client[kQueue][i]
if (request != null) {
streamsToClose.push(detachRequestStreamForClose(request))
if (canReplayRequest(request) && registerGoAwayRefusal(request)) {
retriableRequests.push(request)
} else {
util.errorRequest(client, request, err)
}
}
}
for (let i = 0; i < streamsToClose.length; i++) {
closeStream(streamsToClose[i])
}
if (pendingIdx !== previousPendingIdx) {
const remainingPendingRequests = client[kQueue].slice(previousPendingIdx)
client[kQueue].length = pendingIdx
client[kQueue].push(...retriableRequests, ...remainingPendingRequests)
}
if (client[kHTTP2Session] === this) {
client[kSocket] = null
client[kHTTPContext] = null
client[kHTTP2Session] = null
}
clearHttp2IdleTimeout(this)
clearNoStreamsTimeout(this)
clearRetiredSessionTimeout(this)
if (!this.closed && !this.destroyed) {
this.close()
}
client[kPendingIdx] = pendingIdx
client.emit('disconnect', client[kUrl], [client], err)
client[kResume]()
}
function onHttp2SessionClose () {
const { [kClient]: client, [kHTTP2SessionState]: state, [kSocket]: socket } = this
const err = socket[kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))
if (client[kHTTP2Session] === this) {
client[kSocket] = null
client[kHTTPContext] = null
client[kHTTP2Session] = null
}
clearHttp2IdleTimeout(this)
clearNoStreamsTimeout(this)
clearRetiredSessionTimeout(this)
if (state.ping.interval != null) {
clearInterval(state.ping.interval)
state.ping.interval = null
}
if (client.destroyed) {
assert(client[kPending] === 0)
// Fail entire queue.
const requests = client[kQueue].splice(client[kRunningIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
if (request != null) {
util.errorRequest(client, request, err)
}
}
}
}
function onHttp2SocketClose () {
const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
const session = this[kHTTP2Session]
const client = session[kClient]
if (client[kSocket] !== this) {
// Ignore stale socket closes from a detached GOAWAY session, from a
// retired session that has already announced its own disconnect and from
// any session that has already been replaced. If the session was detached
// without any of those and there is no replacement yet, we still need the
// close event to flush the client state.
if (
session[kReceivedGoAway] ||
session[kHTTP2SessionState].disconnectAnnounced === true ||
(client[kHTTP2Session] != null && client[kHTTP2Session] !== session)
) {
return
}
}
client[kSocket] = null
client[kHTTPContext] = null
if (client[kHTTP2Session] === session) {
client[kHTTP2Session] = null
}
session.destroy(err)
client[kPendingIdx] = client[kRunningIdx]
assert(client[kRunning] === 0)
client.emit('disconnect', client[kUrl], [client], err)
client[kResume]()
}
function onHttp2SocketError (err) {
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
this[kError] = err
if (this[kHTTP2Session]?.[kReceivedGoAway]) {
return
}
this[kHTTP2Session]?.[kClient]?.[kOnError](err)
}
function onHttp2SocketEnd () {
util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
}
function onSocketClose () {
this[kClosed] = true
}
function noop () {}
function closeStreamSession (stream) {
const session = stream[kHTTP2Session]
stream[kHTTP2Session] = null
session[kOpenStreams] -= 1
if (session[kOpenStreams] === 0) {
if (session[kHTTP2SessionState].retired === true) {
// Teardown is driven by onCountedStreamClose once every counted stream
// has physically closed. Until then keep the session ref'd and leave the
// idle timeout disarmed so it cannot cut an in-progress upload short.
return
}
unrefH2Session(session)
setHttp2IdleTimeout(session)
}
}
function onUpgradeStreamClose () {
this.off('error', noop)
const state = this[kRequestStreamState]
this[kRequestStreamState] = null
failUpgradeStream(state, new InformationalError('HTTP/2: stream closed before response headers'))
closeStreamSession(this)
}
// Idempotent terminal cleanup, called from both 'end' and 'close': the
// null-state guard no-ops the later call.
function completeRequestStream () {
const state = this[kRequestStreamState]
if (state == null) {
return
}
// Release the stream first so request references are cleared,
// then complete the response with trailers if available.
releaseRequestStream(this)
if (state.pendingEnd && !state.request.aborted && !state.request.completed) {
state.request.onResponseEnd(state.trailers || {})
} else if (!state.request.aborted && !state.request.completed) {
// The stream closed without a complete response and without reporting an
// error. finalizeRequest() below frees the queue slot either way, so
// without this the request would simply vanish and its caller would never