Package-Level Type Names (total 114, in which 37 are exported)
/* sort exporteds by: | */
ClientConn is the state of a single HTTP/2 client connection to an
HTTP/2 server.
br*bufio.Readerbw*bufio.Writerclosedboolclosingbool
// hold mu; broadcast on flow/closed changes
// whether conn is marked to not be reused for any future requests
// our conn-level flow control quota (cs.outflow is per stream)
fr*Framer
// used by clientConnPool
// if non-nil, the GoAwayFrame we received
// goAway frame's debug data, retained as a string
// HPACK encoder writes into this
henc*hpack.Encoder
// or 0 for never
idleTimer*time.Timer
// peer's conn-level flow control
initialWindowSizeuint32lastActivetime.Time
// time last idle
maxConcurrentStreamsuint32
Settings from peer: (also guarded by wmu)
// guards following
nextStreamIDuint32peerMaxHeaderListSizeuint64peerMaxHeaderTableSizeuint32
// requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
// in flight ping data to notification channel
readLoop goroutine fields:
// closed on error
// set before readerDone is closed
reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests.
Write to reqHeaderMu to lock it, read from it to unlock.
Lock reqmu BEFORE mu or wmu.
// whether conn is being reused; atomic
// true if we've seen a settings frame, false otherwise
// whether being used for a single http.Request
// client-initiated
// incr by ReserveNewRequest; decr on RoundTrip
t*Transport
// usually *tls.Conn, except specialized impls
tconnClosedbool
// nil only for specialized impls
// we sent a SETTINGS frame and haven't heard back
// first write error that has occurred
wmu is held while writing.
Acquire BEFORE mu when holding both, to avoid blocking mu on network writes.
Only acquire both at the same time when changing peer settings.
CanTakeNewRequest reports whether the connection can take a new request,
meaning it has not been closed or received or sent a GOAWAY.
If the caller is going to immediately make a new request on this
connection, use ReserveNewRequest instead.
Close closes the client connection immediately.
In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
Ping sends a PING frame to the server and waits for the ack.
ReserveNewRequest is like CanTakeNewRequest but also reserves a
concurrent stream in cc. The reservation is decremented on the
next call to RoundTrip.
(*ClientConn) RoundTrip(req *http.Request) (*http.Response, error)
SetDoNotReuse marks cc as not reusable for future HTTP requests.
Shutdown gracefully closes the client connection, waiting for running streams to complete.
State returns a snapshot of cc's state.
requires cc.mu be held.
awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams.
Must hold cc.mu.
(*ClientConn) canTakeNewRequestLocked() bool(*ClientConn) closeConn()
closes the client connection immediately. In-flight requests are interrupted.
err is sent to streams.
closes the client connection immediately. In-flight requests are interrupted.
(*ClientConn) closeIfIdle()
countReadFrameError calls Transport.CountError with a string
representing err.
(*ClientConn) decrStreamReservations()(*ClientConn) decrStreamReservationsLocked()
requires cc.wmu be held.
requires cc.wmu be held.
A tls.Conn.Close can hang for a long time if the peer is unresponsive.
Try to shut it down more aggressively.
(*ClientConn) forgetStreamID(id uint32)(*ClientConn) healthCheck()(*ClientConn) idleState() clientConnIdleState(*ClientConn) idleStateLocked() (st clientConnIdleState)(*ClientConn) isDoNotReuseAndIdle() bool(*ClientConn) logf(format string, args ...interface{})
onIdleTimeout is called from a time.AfterFunc goroutine. It will
only be called when we're idle, but because we're coming from a new
goroutine, there could be a new request coming in at the same time,
so this simply calls the synchronized closeIfIdle to shut down this
connection. The timer could just call closeIfIdle, but this is more
clear.
readLoop runs in its own goroutine and reads and dispatches frames.
(*ClientConn) responseHeaderTimeout() time.Duration(*ClientConn) sendGoAway() error(*ClientConn) setGoAway(f *GoAwayFrame)
tooIdleLocked reports whether this connection has been been sitting idle
for too much wall time.
(*ClientConn) vlogf(format string, args ...interface{})(*ClientConn) writeHeader(name, value string)
requires cc.wmu be held
(*ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error)
*ClientConn : database/sql/driver.Pinger
*ClientConn : io.Closer
*ClientConn : net/http.RoundTripper
func ClientConnPool.GetClientConn(req *http.Request, addr string) (*ClientConn, error)
func (*Transport).NewClientConn(c net.Conn) (*ClientConn, error)
func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn
func (*Transport).dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error)
func (*Transport).newClientConn(c net.Conn, singleUse bool) (*ClientConn, error)
func ClientConnPool.MarkDead(*ClientConn)
func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn
func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn
func traceGotConn(req *http.Request, cc *ClientConn, reused bool)
ClientConnPool manages a pool of HTTP/2 client connections.
GetClientConn returns a specific HTTP/2 connection (usually
a TLS-TCP connection) to an HTTP/2 server. On success, the
returned ClientConn accounts for the upcoming RoundTrip
call, so the caller should not omit it. If the caller needs
to, ClientConn.RoundTrip can be called with a bogus
new(http.Request) to release the stream reservation.
( ClientConnPool) MarkDead(*ClientConn)
*clientConnPoolclientConnPoolIdleCloser(interface)noDialClientConnPool
func (*Transport).connPool() ClientConnPool
ClientConnState describes the state of a ClientConn.
Closed is whether the connection is closed.
Closing is whether the connection is in the process of
closing. It may be closing due to shutdown, being a
single-use connection, being marked as DoNotReuse, or
having received a GOAWAY frame.
LastIdle, if non-zero, is when the connection last
transitioned to idle state.
MaxConcurrentStreams is how many concurrent streams the
peer advertised as acceptable. Zero means no SETTINGS
frame has been received yet.
StreamsActive is how many streams are active.
StreamsPending is how many requests have been sent in excess
of the peer's advertised MaxConcurrentStreams setting and
are waiting for other streams to complete.
StreamsReserved is how many streams have been reserved via
ClientConn.ReserveNewRequest.
func (*ClientConn).State() ClientConnState
ConnectionError is an error that results in the termination of the
entire connection.
( ConnectionError) Error() string
ConnectionError : error
A ContinuationFrame is used to continue a sequence of header block fragments.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.10
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
headerFragBuf[]byte
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*ContinuationFrame) HeaderBlockFragment() []byte(*ContinuationFrame) HeadersEnded() bool( ContinuationFrame) String() string(*ContinuationFrame) checkValid()(*ContinuationFrame) invalidate()( ContinuationFrame) writeDebug(buf *bytes.Buffer)
*ContinuationFrame : Frame
ContinuationFrame : expvar.Var
ContinuationFrame : fmt.Stringer
*ContinuationFrame : headersEnder
*ContinuationFrame : headersOrContinuation
ContinuationFrame : context.stringer
ContinuationFrame : github.com/aws/smithy-go/middleware.stringer
*ContinuationFrame : net/http.http2headersEnder
*ContinuationFrame : net/http.http2headersOrContinuation
ContinuationFrame : runtime.stringer
A DataFrame conveys arbitrary, variable-length sequences of octets
associated with a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.1
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
data[]byte
// caller can access []byte fields in the Frame
Data returns the frame's data octets, not including any padding
size byte or padding suffix bytes.
The caller must not retain the returned memory past the next
call to ReadFrame.
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*DataFrame) StreamEnded() bool( DataFrame) String() string(*DataFrame) checkValid()(*DataFrame) invalidate()( DataFrame) writeDebug(buf *bytes.Buffer)
*DataFrame : Frame
DataFrame : expvar.Var
DataFrame : fmt.Stringer
*DataFrame : streamEnder
DataFrame : context.stringer
DataFrame : github.com/aws/smithy-go/middleware.stringer
*DataFrame : net/http.http2streamEnder
DataFrame : runtime.stringer
A Framer reads and writes Frames.
AllowIllegalReads permits the Framer's ReadFrame method
to return non-compliant frames or frame orders.
This is for testing and permits using the Framer to test
other HTTP/2 implementations' conformance to the spec.
It is not compatible with ReadMetaHeaders.
AllowIllegalWrites permits the Framer's Write methods to
write frames that do not conform to the HTTP/2 spec. This
permits using the Framer to test other HTTP/2
implementations' conformance to the spec.
If false, the Write methods will prefer to return an error
rather than comply.
MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE.
It's used only if ReadMetaHeaders is set; 0 means a sane default
(currently 16MB)
If the limit is hit, MetaHeadersFrame.Truncated is set true.
ReadMetaHeaders if non-nil causes ReadFrame to merge
HEADERS and CONTINUATION frames together and return
MetaHeadersFrame instead.
countError is a non-nil func that's called on a frame parse
error with some unique error path token. It's initialized
from Transport.CountError or Server.CountError.
// only use for logging written writes
debugFramerBuf*bytes.BufferdebugReadLoggerffunc(string, ...interface{})debugWriteLoggerffunc(string, ...interface{})errDetailerror
// nil if frames aren't reused (default)
TODO: let getReadBuf be configurable, and use a less memory-pinning
allocator in server.go to minimize memory pinned for many idle conns.
Will probably also need to make frame invalidation have a hook too.
headerBuf[9]bytelastFrameFrame
lastHeaderStream is non-zero if the last frame was an
unfinished HEADERS/CONTINUATION.
logReadsboollogWritesboolmaxReadSizeuint32
// zero means unlimited; TODO: implement
rio.Reader
// cache for default getReadBuf
wio.Writerwbuf[]byte
ErrorDetail returns a more detailed error of the last error
returned by Framer.ReadFrame. For instance, if ReadFrame
returns a StreamError with code PROTOCOL_ERROR, ErrorDetail
will say exactly what was invalid. ErrorDetail is not guaranteed
to return a non-nil value and like the rest of the http2 package,
its return value is not protected by an API compatibility promise.
ErrorDetail is reset after the next call to ReadFrame.
ReadFrame reads a single frame. The returned Frame is only valid
until the next call to ReadFrame.
If the frame is larger than previously set with SetMaxReadFrameSize, the
returned error is ErrFrameTooLarge. Other errors may be of type
ConnectionError, StreamError, or anything else from the underlying
reader.
SetMaxReadFrameSize sets the maximum size of a frame
that will be read by a subsequent call to ReadFrame.
It is the caller's responsibility to advertise this
limit with a SETTINGS frame.
SetReuseFrames allows the Framer to reuse Frames.
If called on a Framer, Frames returned by calls to ReadFrame are only
valid until the next call to ReadFrame.
WriteContinuation writes a CONTINUATION frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteData writes a DATA frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility not to violate the maximum frame size
and to not call other Write methods concurrently.
WriteDataPadded writes a DATA frame with optional padding.
If pad is nil, the padding bit is not sent.
The length of pad must not exceed 255 bytes.
The bytes of pad must all be zero, unless f.AllowIllegalWrites is set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility not to violate the maximum frame size
and to not call other Write methods concurrently.
(*Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error
WriteHeaders writes a single HEADERS frame.
This is a low-level header writing method. Encoding headers and
splitting them into any necessary CONTINUATION frames is handled
elsewhere.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
(*Framer) WritePing(ack bool, data [8]byte) error
WritePriority writes a PRIORITY frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WritePushPromise writes a single PushPromise Frame.
As with Header Frames, This is the low level call for writing
individual frames. Continuation frames are handled elsewhere.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteRSTStream writes a RST_STREAM frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteRawFrame writes a raw frame. This can be used to write
extension frames unknown to this package.
WriteSettings writes a SETTINGS frame with zero or more settings
specified and the ACK bit not set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteWindowUpdate writes a WINDOW_UPDATE frame.
The increment value must be between 1 and 2,147,483,647, inclusive.
If the Stream ID is zero, the window update applies to the
connection as a whole.
checkFrameOrder reports an error if f is an invalid frame to return
next from ReadFrame. Mostly it checks whether HEADERS and
CONTINUATION frames are contiguous.
connError returns ConnectionError(code) but first
stashes away a public reason to the caller can optionally relay it
to the peer before hanging up on them. This might help others debug
their implementations.
(*Framer) endWrite() error(*Framer) logWrite()(*Framer) maxHeaderListSize() uint32(*Framer) maxHeaderStringLen() int
readMetaFrame returns 0 or more CONTINUATION frames from fr and
merge them into the provided hf and returns a MetaHeadersFrame
with the decoded hpack values.
(*Framer) startWrite(ftype FrameType, flags Flags, streamID uint32)
startWriteDataPadded is WriteDataPadded, but only writes the frame to the Framer's internal buffer.
The caller should call endWrite to flush the frame to the underlying writer.
(*Framer) writeByte(v byte)(*Framer) writeBytes(v []byte)(*Framer) writeUint16(v uint16)(*Framer) writeUint32(v uint32)
func NewFramer(w io.Writer, r io.Reader) *Framer
FrameWriteRequest is a request to write a frame.
done, if non-nil, must be a buffered channel with space for
1 message and is sent the return value from write (or an
earlier error) when the frame has been written.
stream is the stream on which this frame will be written.
nil for non-stream frames like PING and SETTINGS.
nil for RST_STREAM streams, which use the StreamError.StreamID field instead.
write is the interface value that does the writing, once the
WriteScheduler has selected this frame to write. The write
functions are all defined in write.go.
Consume consumes min(n, available) bytes from this frame, where available
is the number of flow control bytes available on the stream. Consume returns
0, 1, or 2 frames, where the integer return value gives the number of frames
returned.
If flow control prevents consuming any bytes, this returns (_, _, 0). If
the entire frame was consumed, this returns (wr, _, 1). Otherwise, this
returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and
'rest' contains the remaining bytes. The consumed bytes are deducted from the
underlying stream's flow control budget.
DataSize returns the number of flow control bytes that must be consumed
to write this entire frame. This is 0 for non-DATA frames.
StreamID returns the id of the stream this frame will be written to.
0 is used for non-stream frames such as PING and SETTINGS.
String is for debugging only.
isControl reports whether wr is a control frame for MaxQueuedControlFrames
purposes. That includes non-stream frames and RST_STREAM frames.
replyToWriter sends err to wr.done and panics if the send must block
This does nothing if wr.done is nil.
FrameWriteRequest : expvar.Var
FrameWriteRequest : fmt.Stringer
FrameWriteRequest : context.stringer
FrameWriteRequest : github.com/aws/smithy-go/middleware.stringer
FrameWriteRequest : runtime.stringer
func FrameWriteRequest.Consume(n int32) (FrameWriteRequest, FrameWriteRequest, int)
func FrameWriteRequest.Consume(n int32) (FrameWriteRequest, FrameWriteRequest, int)
func WriteScheduler.Pop() (wr FrameWriteRequest, ok bool)
func WriteScheduler.Push(wr FrameWriteRequest)
A GoAwayFrame informs the remote peer to stop creating streams on this connection.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.8
ErrCodeErrCodeFrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
LastStreamIDuint32debugData[]byte
// caller can access []byte fields in the Frame
DebugData returns any debug data in the GOAWAY frame. Its contents
are not defined.
The caller must not retain the returned memory past the next
call to ReadFrame.
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( GoAwayFrame) String() string(*GoAwayFrame) checkValid()(*GoAwayFrame) invalidate()( GoAwayFrame) writeDebug(buf *bytes.Buffer)
*GoAwayFrame : Frame
GoAwayFrame : expvar.Var
GoAwayFrame : fmt.Stringer
GoAwayFrame : context.stringer
GoAwayFrame : github.com/aws/smithy-go/middleware.stringer
GoAwayFrame : runtime.stringer
func (*ClientConn).setGoAway(f *GoAwayFrame)
A HeadersFrame is used to open a stream and additionally carries a
header block fragment.
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
Priority is set if FlagHeadersPriority is set in the FrameHeader.
// caller can access []byte fields in the Frame
// not owned
(*HeadersFrame) HasPriority() bool
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*HeadersFrame) HeaderBlockFragment() []byte(*HeadersFrame) HeadersEnded() bool(*HeadersFrame) StreamEnded() bool( HeadersFrame) String() string(*HeadersFrame) checkValid()(*HeadersFrame) invalidate()( HeadersFrame) writeDebug(buf *bytes.Buffer)
*HeadersFrame : Frame
HeadersFrame : expvar.Var
HeadersFrame : fmt.Stringer
*HeadersFrame : headersEnder
*HeadersFrame : headersOrContinuation
*HeadersFrame : streamEnder
HeadersFrame : context.stringer
HeadersFrame : github.com/aws/smithy-go/middleware.stringer
*HeadersFrame : net/http.http2headersEnder
*HeadersFrame : net/http.http2headersOrContinuation
*HeadersFrame : net/http.http2streamEnder
HeadersFrame : runtime.stringer
func (*Framer).readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error)
HeadersFrameParam are the parameters for writing a HEADERS frame.
BlockFragment is part (or all) of a Header Block.
EndHeaders indicates that this frame contains an entire
header block and is not followed by any
CONTINUATION frames.
EndStream indicates that the header block is the last that
the endpoint will send for the identified stream. Setting
this flag causes the stream to enter one of "half closed"
states.
PadLength is the optional number of bytes of zeros to add
to this frame.
Priority, if non-zero, includes stream priority information
in the HEADER frame.
StreamID is the required Stream ID to initiate.
func (*Framer).WriteHeaders(p HeadersFrameParam) error
A MetaHeadersFrame is the representation of one HEADERS frame and
zero or more contiguous CONTINUATION frames and the decoding of
their HPACK-encoded contents.
This type of frame does not appear on the wire and is only returned
by the Framer when Framer.ReadMetaHeaders is set.
Fields are the fields contained in the HEADERS and
CONTINUATION frames. The underlying slice is owned by the
Framer and must not be retained after the next call to
ReadFrame.
Fields are guaranteed to be in the correct http2 order and
not have unknown pseudo header fields or invalid header
field names or values. Required pseudo header fields may be
missing, however. Use the MetaHeadersFrame.Pseudo accessor
method access pseudo headers.
HeadersFrame*HeadersFrameHeadersFrame.FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
Priority is set if FlagHeadersPriority is set in the FrameHeader.
Truncated is whether the max header list size limit was hit
and Fields is incomplete. The hpack decoder state is still
valid, however.
// caller can access []byte fields in the Frame
// not owned
( MetaHeadersFrame) HasPriority() bool
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( MetaHeadersFrame) HeaderBlockFragment() []byte( MetaHeadersFrame) HeadersEnded() bool
PseudoFields returns the pseudo header fields of mh.
The caller does not own the returned slice.
PseudoValue returns the given pseudo header field's value.
The provided pseudo field should not contain the leading colon.
RegularFields returns the regular (non-pseudo) header fields of mh.
The caller does not own the returned slice.
( MetaHeadersFrame) StreamEnded() bool( MetaHeadersFrame) String() string(*MetaHeadersFrame) checkPseudos() error( MetaHeadersFrame) checkValid()( MetaHeadersFrame) invalidate()( MetaHeadersFrame) writeDebug(buf *bytes.Buffer)
MetaHeadersFrame : Frame
MetaHeadersFrame : expvar.Var
MetaHeadersFrame : fmt.Stringer
MetaHeadersFrame : headersEnder
MetaHeadersFrame : headersOrContinuation
MetaHeadersFrame : streamEnder
MetaHeadersFrame : context.stringer
MetaHeadersFrame : github.com/aws/smithy-go/middleware.stringer
MetaHeadersFrame : net/http.http2headersEnder
MetaHeadersFrame : net/http.http2headersOrContinuation
MetaHeadersFrame : net/http.http2streamEnder
MetaHeadersFrame : runtime.stringer
func (*Framer).readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error)
OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.
PusherID is zero if the stream was initiated by the client. Otherwise,
PusherID names the stream that pushed the newly opened stream.
func WriteScheduler.OpenStream(streamID uint32, options OpenStreamOptions)
A PingFrame is a mechanism for measuring a minimal round trip time
from the sender, as well as determining whether an idle connection
is still functional.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.7
Data[8]byteFrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*PingFrame) IsAck() bool( PingFrame) String() string(*PingFrame) checkValid()(*PingFrame) invalidate()( PingFrame) writeDebug(buf *bytes.Buffer)
*PingFrame : Frame
PingFrame : expvar.Var
PingFrame : fmt.Stringer
PingFrame : context.stringer
PingFrame : github.com/aws/smithy-go/middleware.stringer
PingFrame : runtime.stringer
A PriorityFrame specifies the sender-advised priority of a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.3
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
PriorityParamPriorityParam
Exclusive is whether the dependency is exclusive.
StreamDep is a 31-bit stream identifier for the
stream that this stream depends on. Zero means no
dependency.
Weight is the stream's zero-indexed weight. It should be
set together with StreamDep, or neither should be set. Per
the spec, "Add one to the value to obtain a weight between
1 and 256."
// caller can access []byte fields in the Frame
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( PriorityFrame) IsZero() bool( PriorityFrame) String() string(*PriorityFrame) checkValid()(*PriorityFrame) invalidate()( PriorityFrame) writeDebug(buf *bytes.Buffer)
*PriorityFrame : Frame
PriorityFrame : expvar.Var
PriorityFrame : fmt.Stringer
PriorityFrame : context.stringer
PriorityFrame : github.com/aws/smithy-go/middleware.stringer
PriorityFrame : github.com/go-pg/zerochecker.isZeroer
PriorityFrame : github.com/vmihailenco/msgpack/v5.isZeroer
PriorityFrame : runtime.stringer
PriorityParam are the stream prioritzation parameters.
Exclusive is whether the dependency is exclusive.
StreamDep is a 31-bit stream identifier for the
stream that this stream depends on. Zero means no
dependency.
Weight is the stream's zero-indexed weight. It should be
set together with StreamDep, or neither should be set. Per
the spec, "Add one to the value to obtain a weight between
1 and 256."
( PriorityParam) IsZero() bool
PriorityParam : github.com/go-pg/zerochecker.isZeroer
PriorityParam : github.com/vmihailenco/msgpack/v5.isZeroer
func (*Framer).WritePriority(streamID uint32, p PriorityParam) error
func WriteScheduler.AdjustStream(streamID uint32, priority PriorityParam)
PriorityWriteSchedulerConfig configures a priorityWriteScheduler.
MaxClosedNodesInTree controls the maximum number of closed streams to
retain in the priority tree. Setting this to zero saves a small amount
of memory at the cost of performance.
See RFC 7540, Section 5.3.4:
"It is possible for a stream to become closed while prioritization
information ... is in transit. ... This potentially creates suboptimal
prioritization, since the stream could be given a priority that is
different from what is intended. To avoid these problems, an endpoint
SHOULD retain stream prioritization state for a period after streams
become closed. The longer state is retained, the lower the chance that
streams are assigned incorrect or default priority values."
MaxIdleNodesInTree controls the maximum number of idle streams to
retain in the priority tree. Setting this to zero saves a small amount
of memory at the cost of performance.
See RFC 7540, Section 5.3.4:
Similarly, streams that are in the "idle" state can be assigned
priority or become a parent of other streams. This allows for the
creation of a grouping node in the dependency tree, which enables
more flexible expressions of priority. Idle streams begin with a
default priority (Section 5.3.5).
ThrottleOutOfOrderWrites enables write throttling to help ensure that
data is delivered in priority order. This works around a race where
stream B depends on stream A and both streams are about to call Write
to queue DATA frames. If B wins the race, a naive scheduler would eagerly
write as much data from B as possible, but this is suboptimal because A
is a higher-priority stream. With throttling enabled, we write a small
amount of data from B to minimize the amount of bandwidth that B can
steal from A.
func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler
A PushPromiseFrame is used to initiate a server stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.6
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
PromiseIDuint32
// caller can access []byte fields in the Frame
// not owned
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*PushPromiseFrame) HeaderBlockFragment() []byte(*PushPromiseFrame) HeadersEnded() bool( PushPromiseFrame) String() string(*PushPromiseFrame) checkValid()(*PushPromiseFrame) invalidate()( PushPromiseFrame) writeDebug(buf *bytes.Buffer)
*PushPromiseFrame : Frame
PushPromiseFrame : expvar.Var
PushPromiseFrame : fmt.Stringer
*PushPromiseFrame : headersEnder
*PushPromiseFrame : headersOrContinuation
PushPromiseFrame : context.stringer
PushPromiseFrame : github.com/aws/smithy-go/middleware.stringer
*PushPromiseFrame : net/http.http2headersEnder
*PushPromiseFrame : net/http.http2headersOrContinuation
PushPromiseFrame : runtime.stringer
PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
BlockFragment is part (or all) of a Header Block.
EndHeaders indicates that this frame contains an entire
header block and is not followed by any
CONTINUATION frames.
PadLength is the optional number of bytes of zeros to add
to this frame.
PromiseID is the required Stream ID which this
Push Promises
StreamID is the required Stream ID to initiate.
func (*Framer).WritePushPromise(p PushPromiseParam) error
RoundTripOpt are options for the Transport.RoundTripOpt method.
OnlyCachedConn controls whether RoundTripOpt may
create a new TCP connection. If set true and
no cached connection is available, RoundTripOpt
will return ErrNoCachedConn.
func (*Transport).RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error)
A RSTStreamFrame allows for abnormal termination of a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.4
ErrCodeErrCodeFrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( RSTStreamFrame) String() string(*RSTStreamFrame) checkValid()(*RSTStreamFrame) invalidate()( RSTStreamFrame) writeDebug(buf *bytes.Buffer)
*RSTStreamFrame : Frame
RSTStreamFrame : expvar.Var
RSTStreamFrame : fmt.Stringer
RSTStreamFrame : context.stringer
RSTStreamFrame : github.com/aws/smithy-go/middleware.stringer
RSTStreamFrame : runtime.stringer
ServeConnOpts are options for the Server.ServeConn method.
BaseConfig optionally sets the base configuration
for values. If nil, defaults are used.
Context is the base context to use.
If nil, context.Background is used.
Handler specifies which handler to use for processing
requests. If nil, BaseConfig.Handler is used. If BaseConfig
or BaseConfig.Handler is nil, http.DefaultServeMux is used.
SawClientPreface is set if the HTTP/2 connection preface
has already been read from the connection.
Settings is the decoded contents of the HTTP2-Settings header
in an h2c upgrade request.
UpgradeRequest is an initial request received on a connection
undergoing an h2c upgrade. The request body must have been
completely read from the connection before calling ServeConn,
and the 101 Switching Protocols response written.
(*ServeConnOpts) baseConfig() *http.Server(*ServeConnOpts) context() context.Context(*ServeConnOpts) handler() http.Handler
func (*Server).ServeConn(c net.Conn, opts *ServeConnOpts)
func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx context.Context, cancel func())
Server is an HTTP/2 server.
CountError, if non-nil, is called on HTTP/2 server errors.
It's intended to increment a metric for monitoring, such
as an expvar or Prometheus metric.
The errType consists of only ASCII word characters.
IdleTimeout specifies how long until idle clients should be
closed with a GOAWAY frame. PING frames are not considered
activity for the purposes of IdleTimeout.
MaxConcurrentStreams optionally specifies the number of
concurrent streams that each client may have open at a
time. This is unrelated to the number of http.Handler goroutines
which may be active globally, which is MaxHandlers.
If zero, MaxConcurrentStreams defaults to at least 100, per
the HTTP/2 spec's recommendations.
MaxDecoderHeaderTableSize optionally specifies the http2
SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
informs the remote endpoint of the maximum size of the header compression
table used to decode header blocks, in octets. If zero, the default value
of 4096 is used.
MaxEncoderHeaderTableSize optionally specifies an upper limit for the
header compression table used for encoding request headers. Received
SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
the default value of 4096 is used.
MaxHandlers limits the number of http.Handler ServeHTTP goroutines
which may run at a time over all connections.
Negative or zero no limit.
TODO: implement
MaxReadFrameSize optionally specifies the largest frame
this server is willing to read. A valid value is between
16k and 16M, inclusive. If zero or otherwise invalid, a
default value is used.
MaxUploadBufferPerConnection is the size of the initial flow
control window for each connections. The HTTP/2 spec does not
allow this to be smaller than 65535 or larger than 2^32-1.
If the value is outside this range, a default value will be
used instead.
MaxUploadBufferPerStream is the size of the initial flow control
window for each stream. The HTTP/2 spec does not allow this to
be larger than 2^32-1. If the value is zero or larger than the
maximum, a default value will be used instead.
NewWriteScheduler constructs a write scheduler for a connection.
If nil, a default scheduler is chosen.
PermitProhibitedCipherSuites, if true, permits the use of
cipher suites prohibited by the HTTP/2 spec.
Internal state. This is a pointer (rather than embedded directly)
so that we don't embed a Mutex in this struct, which will make the
struct non-copyable, which might break some callers.
ServeConn serves HTTP/2 requests on the provided connection and
blocks until the connection is no longer readable.
ServeConn starts speaking HTTP/2 assuming that c has not had any
reads or writes. It writes its initial settings frame and expects
to be able to read the preface and settings frame from the
client. If c has a ConnectionState method like a *tls.Conn, the
ConnectionState is used to verify the TLS ciphersuite and to set
the Request.TLS field in Handlers.
ServeConn does not support h2c by itself. Any h2c support must be
implemented in terms of providing a suitably-behaving net.Conn.
The opts parameter is optional. If nil, default values are used.
(*Server) initialConnRecvWindowSize() int32(*Server) initialStreamRecvWindowSize() int32(*Server) maxConcurrentStreams() uint32(*Server) maxDecoderHeaderTableSize() uint32(*Server) maxEncoderHeaderTableSize() uint32
maxQueuedControlFrames is the maximum number of control frames like
SETTINGS, PING and RST_STREAM that will be queued for writing before
the connection is closed to prevent memory exhaustion attacks.
(*Server) maxReadFrameSize() uint32
func ConfigureServer(s *http.Server, conf *Server) error
Setting is a setting parameter: which setting it is, and its value.
ID is which setting is being set.
See https://httpwg.org/specs/rfc7540.html#SettingFormat
Val is the value.
( Setting) String() string
Valid reports whether the setting is valid.
Setting : expvar.Var
Setting : fmt.Stringer
Setting : context.stringer
Setting : github.com/aws/smithy-go/middleware.stringer
Setting : runtime.stringer
func (*SettingsFrame).Setting(i int) Setting
func (*Framer).WriteSettings(settings ...Setting) error
A SettingsFrame conveys configuration parameters that affect how
endpoints communicate, such as preferences and constraints on peer
behavior.
See https://httpwg.org/specs/rfc7540.html#SETTINGS
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
p[]byte
ForeachSetting runs fn for each setting.
It stops and returns the first error.
HasDuplicates reports whether f contains any duplicate setting IDs.
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*SettingsFrame) IsAck() bool(*SettingsFrame) NumSettings() int
Setting returns the setting from the frame at the given 0-based index.
The index must be >= 0 and less than f.NumSettings().
( SettingsFrame) String() string(*SettingsFrame) Value(id SettingID) (v uint32, ok bool)(*SettingsFrame) checkValid()(*SettingsFrame) invalidate()( SettingsFrame) writeDebug(buf *bytes.Buffer)
*SettingsFrame : Frame
SettingsFrame : expvar.Var
SettingsFrame : fmt.Stringer
SettingsFrame : context.stringer
SettingsFrame : github.com/aws/smithy-go/middleware.stringer
SettingsFrame : runtime.stringer
Transport is an HTTP/2 Transport.
A Transport internally caches connections to servers. It is safe
for concurrent use by multiple goroutines.
AllowHTTP, if true, permits HTTP/2 requests using the insecure,
plain-text "http" scheme. Note that this does not enable h2c support.
ConnPool optionally specifies an alternate connection pool to use.
If nil, the default is used.
CountError, if non-nil, is called on HTTP/2 transport errors.
It's intended to increment a metric for monitoring, such
as an expvar or Prometheus metric.
The errType consists of only ASCII word characters.
DialTLS specifies an optional dial function for creating
TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
Deprecated: Use DialTLSContext instead, which allows the transport
to cancel dials as soon as they are no longer needed.
If both are set, DialTLSContext takes priority.
DialTLSContext specifies an optional dial function with context for
creating TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
If the returned net.Conn has a ConnectionState method like tls.Conn,
it will be used to set http.Response.TLS.
DisableCompression, if true, prevents the Transport from
requesting compression with an "Accept-Encoding: gzip"
request header when the Request contains no existing
Accept-Encoding value. If the Transport requests gzip on
its own and gets a gzipped response, it's transparently
decoded in the Response.Body. However, if the user
explicitly requested gzip it is not automatically
uncompressed.
MaxDecoderHeaderTableSize optionally specifies the http2
SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
informs the remote endpoint of the maximum size of the header compression
table used to decode header blocks, in octets. If zero, the default value
of 4096 is used.
MaxEncoderHeaderTableSize optionally specifies an upper limit for the
header compression table used for encoding request headers. Received
SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
the default value of 4096 is used.
MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
send in the initial settings frame. It is how many bytes
of response headers are allowed. Unlike the http2 spec, zero here
means to use a default limit (currently 10MB). If you actually
want to advertise an unlimited value to the peer, Transport
interprets the highest possible value here (0xffffffff or 1<<32-1)
to mean no limit.
MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
initial settings frame. It is the size in bytes of the largest frame
payload that the sender is willing to receive. If 0, no setting is
sent, and the value is provided by the peer, which should be 16384
according to the spec:
https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
Values are bounded in the range 16k to 16M.
PingTimeout is the timeout after which the connection will be closed
if a response to Ping is not received.
Defaults to 15s.
ReadIdleTimeout is the timeout after which a health check using ping
frame will be carried out if no frame is received on the connection.
Note that a ping response will is considered a received frame, so if
there is no other traffic on the connection, the health check will
be performed every ReadIdleTimeout interval.
If zero, no health check is performed.
StrictMaxConcurrentStreams controls whether the server's
SETTINGS_MAX_CONCURRENT_STREAMS should be respected
globally. If false, new TCP connections are created to the
server as needed to keep each under the per-connection
SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
a global limit and callers of RoundTrip block when needed,
waiting for their turn.
TLSClientConfig specifies the TLS configuration to use with
tls.Client. If nil, the default configuration is used.
WriteByteTimeout is the timeout after which the connection will be
closed no data can be written to it. The timeout begins when data is
available to write, and is extended whenever any bytes are written.
connPoolOncesync.Once
// non-nil version of ConnPool
t1, if non-nil, is the standard library Transport using
this transport. Its settings are used (but not its
RoundTrip method, etc).
CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle.
It does not interrupt any connections currently in use.
(*Transport) NewClientConn(c net.Conn) (*ClientConn, error)(*Transport) RoundTrip(req *http.Request) (*http.Response, error)
RoundTripOpt is like RoundTrip, but takes options.
(*Transport) connPool() ClientConnPool(*Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error)(*Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error)
dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS
connection.
(*Transport) disableCompression() bool
disableKeepAlives reports whether connections should be closed as
soon as possible after handling the first request.
(*Transport) expectContinueTimeout() time.Duration(*Transport) idleConnTimeout() time.Duration(*Transport) initConnPool()(*Transport) logf(format string, args ...interface{})(*Transport) maxDecoderHeaderTableSize() uint32(*Transport) maxEncoderHeaderTableSize() uint32(*Transport) maxFrameReadSize() uint32(*Transport) maxHeaderListSize() uint32(*Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error)(*Transport) newTLSConfig(host string) *tls.Config(*Transport) pingTimeout() time.Duration(*Transport) vlogf(format string, args ...interface{})
*Transport : net/http.RoundTripper
*Transport : net/http.h2Transport
*Transport : net/http/httptest.closeIdleTransport
func ConfigureTransports(t1 *http.Transport) (*Transport, error)
func configureTransports(t1 *http.Transport) (*Transport, error)
An UnknownFrame is the frame type returned when the frame type is unknown
or no specific frame type parser exists.
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
p[]byte
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
Payload returns the frame's payload (after the header). It is not
valid to call this method after a subsequent call to
Framer.ReadFrame, nor is it valid to retain the returned slice.
The memory is owned by the Framer and is invalidated when the next
frame is read.
( UnknownFrame) String() string(*UnknownFrame) checkValid()(*UnknownFrame) invalidate()( UnknownFrame) writeDebug(buf *bytes.Buffer)
*UnknownFrame : Frame
UnknownFrame : expvar.Var
UnknownFrame : fmt.Stringer
UnknownFrame : context.stringer
UnknownFrame : github.com/aws/smithy-go/middleware.stringer
UnknownFrame : runtime.stringer
A WindowUpdateFrame is used to implement flow control.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.9
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// never read with high bit set
// caller can access []byte fields in the Frame
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( WindowUpdateFrame) String() string(*WindowUpdateFrame) checkValid()(*WindowUpdateFrame) invalidate()( WindowUpdateFrame) writeDebug(buf *bytes.Buffer)
*WindowUpdateFrame : Frame
WindowUpdateFrame : expvar.Var
WindowUpdateFrame : fmt.Stringer
WindowUpdateFrame : context.stringer
WindowUpdateFrame : github.com/aws/smithy-go/middleware.stringer
WindowUpdateFrame : runtime.stringer
WriteScheduler is the interface implemented by HTTP/2 write schedulers.
Methods are never called concurrently.
AdjustStream adjusts the priority of the given stream. This may be called
on a stream that has not yet been opened or has been closed. Note that
RFC 7540 allows PRIORITY frames to be sent on streams in any state. See:
https://tools.ietf.org/html/rfc7540#section-5.1
CloseStream closes a stream in the write scheduler. Any frames queued on
this stream should be discarded. It is illegal to call this on a stream
that is not open -- the call may panic.
OpenStream opens a new stream in the write scheduler.
It is illegal to call this with streamID=0 or with a streamID that is
already open -- the call may panic.
Pop dequeues the next frame to write. Returns false if no frames can
be written. Frames with a given wr.StreamID() are Pop'd in the same
order they are Push'd, except RST_STREAM frames. No frames should be
discarded except by CloseStream.
Push queues a frame in the scheduler. In most cases, this will not be
called with wr.StreamID()!=0 unless that stream is currently open. The one
exception is RST_STREAM frames, which may be sent on idle or closed streams.
*priorityWriteScheduler
*randomWriteScheduler
func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler
func NewRandomWriteScheduler() WriteScheduler
A bodyReadMsg tells the server loop that the http.Handler read n
bytes of the DATA from the client on the given stream.
nintst*stream
bufferedWriter is a buffered writer that writes to w.
Its buffered writer is lazily allocated as needed, to minimize
idle memory usage with many connections.
// non-nil when data is buffered
// immutable
(*bufferedWriter) Available() int(*bufferedWriter) Flush() error(*bufferedWriter) Write(p []byte) (n int, err error)
*bufferedWriter : io.Writer
func newBufferedWriter(w io.Writer) *bufferedWriter
TODO: use singleflight for dialing and addConnCalls?
// in-flight addConnIfNeeded calls
TODO: add support for sharing conns based on cert names
(e.g. share conn for googleapis.com and appspot.com)
// key is host:port
// currently in-flight dials
keysmap[*ClientConn][]string
// TODO: maybe switch to RWMutex
t*Transport(*clientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error)(*clientConnPool) MarkDead(cc *ClientConn)
addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't
already exist. It coalesces concurrent calls with the same key.
This is used by the http1 Transport code when it creates a new connection. Because
the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know
the protocol), it can get into a situation where it has multiple TLS connections.
This code decides which ones live or die.
The return value used is whether c was used.
c is never closed.
p.mu must be held
(*clientConnPool) closeIdleConnections()(*clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error)
requires p.mu is held.
*clientConnPool : ClientConnPool
*clientConnPool : clientConnPoolIdleCloser
clientConnPoolIdleCloser is the interface implemented by ClientConnPool
implementations which can close their idle connections.
GetClientConn returns a specific HTTP/2 connection (usually
a TLS-TCP connection) to an HTTP/2 server. On success, the
returned ClientConn accounts for the upcoming RoundTrip
call, so the caller should not omit it. If the caller needs
to, ClientConn.RoundTrip can be called with a bogus
new(http.Request) to release the stream reservation.
( clientConnPoolIdleCloser) MarkDead(*ClientConn)( clientConnPoolIdleCloser) closeIdleConnections()
*clientConnPoolnoDialClientConnPool
clientConnPoolIdleCloser : ClientConnPool
clientStream is the state for a single HTTP/2 stream. One of these
is created for each Transport.RoundTrip call.
IDuint32
// closed to signal stream should end immediately
// set if abort is closed
abortOncesync.Once
// buffered pipe with the flow-controlled response payload
// -1 means unknown; owned by transportResponseBody.Read
cc*ClientConn
Fields of Request that we may access even after the response body is closed.
// closed after the stream is in the closed state
owned by clientConnReadLoop:
// got the first response byte
// guarded by cc.mu
// guarded by cc.mu
isHeadbool
// number of 1xx responses seen
// buffered; written to if a 100 is received
// got first MetaHeadersFrame (actual headers)
// got optional second MetaHeadersFrame (trailers)
// closed when the peer sends an END_STREAM flag
// read loop reset the stream
// peer sent an END_STREAM flag
// sticky read error; owned by transportResponseBody.Read
reqBodyio.ReadCloser
// guarded by cc.mu; non-nil on Close, closed when done
// -1 means unknown
reqCancel<-chan struct{}requestedGzipbool
// set if respHeaderRecv is closed
// client's Response.Trailer
// closed when headers are received
owned by writeRequest:
// sent an END_STREAM flag to the peer
sentHeadersbool
// or nil
// accumulated trailers
(*clientStream) abortRequestBodyWrite()(*clientStream) abortStream(err error)(*clientStream) abortStreamLocked(err error)
awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
control tokens from the server.
It returns either the non-zero number of tokens taken or an error
if the stream is dead.
cleanupWriteRequest performs post-request tasks.
If err (the result of writeRequest) is non-nil and the stream is not closed,
cleanupWriteRequest will send a reset to the peer.
(*clientStream) closeReqBodyLocked()(*clientStream) copyTrailers()
doRequest runs for the duration of the request lifetime.
It sends the request and performs post-request cleanup (closing Request.Body, etc.).
(*clientStream) encodeAndWriteHeaders(req *http.Request) error
frameScratchBufferLen returns the length of a buffer to use for
outgoing request bodies to read/write to/from.
It returns max(1, min(peer's advertised max frame size,
Request.ContentLength+1, 512KB)).
get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
if any. It returns nil if not set or if the Go version is too old.
writeRequest sends a request.
It returns nil after the request is written, the response read,
and the request stream is half-closed by the peer.
It returns non-nil if the request ends otherwise.
If the returned error is StreamError, the error Code may be used in resetting the stream.
(*clientStream) writeRequestBody(req *http.Request) (err error)
func (*ClientConn).addStreamLocked(cs *clientStream)
func (*ClientConn).awaitOpenSlotForStreamLocked(cs *clientStream) error
A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
Close marks the closeWaiter as closed and unblocks any waiters.
Init makes a closeWaiter usable.
It exists because so a closeWaiter value can be placed inside a
larger struct and have the Mutex and Cond's memory in the same
allocation.
Wait waits for the closeWaiter to become closed.
connError represents an HTTP/2 ConnectionError error code, along
with a string (for debugging) explaining why.
Errors of this type are only returned by the frame parser functions
and converted into ConnectionError(Code), after stashing away
the Reason into the Framer's errDetail field, accessible via
the (*Framer).ErrorDetail method.
// the ConnectionError error code
// additional reason
( connError) Error() string
connError : error
dataBuffer is an io.ReadWriter backed by a list of data chunks.
Each dataBuffer is used to read DATA frames on a single stream.
The buffer is divided into chunks so the server can limit the
total memory used by a single connection without limiting the
request body size on any single stream.
chunks[][]byte
// we expect at least this many bytes in future Write calls (ignored if <= 0)
// next byte to read is chunks[0][r]
// total buffered bytes
// next byte to write is chunks[len(chunks)-1][w]
Len returns the number of bytes of the unread portion of the buffer.
Read copies bytes from the buffer into p.
It is an error to read when no data is available.
Write appends p to the buffer.
(*dataBuffer) bytesFromFirstChunk() []byte(*dataBuffer) lastChunkOrAlloc(want int64) []byte
*dataBuffer : io.Reader
*dataBuffer : io.ReadWriter
*dataBuffer : io.Writer
*dataBuffer : pipeBuffer
*dataBuffer : net/http.http2pipeBuffer
dialCall is an in-flight Transport dial call to a host.
the context associated with the request
that created this dialCall
// closed when done
// valid after done is closed
p*clientConnPool
// valid after done is closed
run in its own goroutine.
func shouldRetryDial(call *dialCall, req *http.Request) bool
a frameParser parses a frame given its FrameHeader and payload
bytes. The length of payload will always equal fh.Length (which
might be 0).
func typeFrameParser(t FrameType) frameParser
frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
// result of the writeFrame call
// what was written (or attempted)
A gate lets two goroutines coordinate their activities.
( gate) Done()( gate) Wait()
6.9.1 The Flow Control Window
"If a sender receives a WINDOW_UPDATE that causes a flow control
window to exceed this maximum it MUST terminate either the stream
or the connection, as appropriate. For streams, [...]; for the
connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code."
( goAwayFlowError) Error() string
goAwayFlowError : error
gzipReader wraps a response body so it can lazily
call gzip.NewReader on the first call to Read
// underlying Response.Body
// sticky error
// lazily-initialized gzip reader
(*gzipReader) Close() error(*gzipReader) Read(p []byte) (n int, err error)
*gzipReader : io.Closer
*gzipReader : io.ReadCloser
*gzipReader : io.Reader
incomparable is a zero-width, non-comparable type. Adding it to a struct
makes that struct also non-comparable, and generally doesn't add
any size (as long as it's first).
inflow accounts for an inbound flow control window.
It tracks both the latest window sent to the peer (used for enforcement)
and the accumulated unsent window.
availint32unsentint32
add adds n bytes to the window, with a maximum window size of max,
indicating that the peer can now send us more data.
For example, the user read from a {Request,Response} body and consumed
some of the buffered data, so the peer can now send more.
It returns the number of bytes to send in a WINDOW_UPDATE frame to the peer.
Window updates are accumulated and sent when the unsent capacity
is at least inflowMinRefresh or will at least double the peer's available window.
init sets the initial window.
take attempts to take n bytes from the peer's flow control window.
It reports whether the window has available capacity.
func takeInflows(f1, f2 *inflow, n uint32) bool
noCachedConnError is the concrete type of ErrNoCachedConn, which
needs to be detected by net/http regardless of whether it's its
bundled version (in h2_bundle.go with a rewritten type name) or
from a user's x/net/http2. As such, as it has a unique method name
(IsHTTP2NoCachedConnError) that net/http sniffs for via func
isNoCachedConnError.
( noCachedConnError) Error() string( noCachedConnError) IsHTTP2NoCachedConnError()
noCachedConnError : error
noDialClientConnPool is an implementation of http2.ClientConnPool
which never dials. We let the HTTP/1.1 client dial and use its TLS
connection instead.
clientConnPool*clientConnPool
// in-flight addConnIfNeeded calls
TODO: add support for sharing conns based on cert names
(e.g. share conn for googleapis.com and appspot.com)
// key is host:port
// currently in-flight dials
clientConnPool.keysmap[*ClientConn][]string
// TODO: maybe switch to RWMutex
clientConnPool.t*Transport( noDialClientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error)( noDialClientConnPool) MarkDead(cc *ClientConn)
addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't
already exist. It coalesces concurrent calls with the same key.
This is used by the http1 Transport code when it creates a new connection. Because
the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know
the protocol), it can get into a situation where it has multiple TLS connections.
This code decides which ones live or die.
The return value used is whether c was used.
c is never closed.
p.mu must be held
( noDialClientConnPool) closeIdleConnections()( noDialClientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error)
requires p.mu is held.
noDialClientConnPool : ClientConnPool
noDialClientConnPool : clientConnPoolIdleCloser
noDialH2RoundTripper is a RoundTripper which only tries to complete the request
if there's already has a cached connection to the host.
(The field is exported so it can be accessed via reflect from net/http; tested
by TestNoDialH2RoundTripperType)
Transport*Transport
AllowHTTP, if true, permits HTTP/2 requests using the insecure,
plain-text "http" scheme. Note that this does not enable h2c support.
ConnPool optionally specifies an alternate connection pool to use.
If nil, the default is used.
CountError, if non-nil, is called on HTTP/2 transport errors.
It's intended to increment a metric for monitoring, such
as an expvar or Prometheus metric.
The errType consists of only ASCII word characters.
DialTLS specifies an optional dial function for creating
TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
Deprecated: Use DialTLSContext instead, which allows the transport
to cancel dials as soon as they are no longer needed.
If both are set, DialTLSContext takes priority.
DialTLSContext specifies an optional dial function with context for
creating TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
If the returned net.Conn has a ConnectionState method like tls.Conn,
it will be used to set http.Response.TLS.
DisableCompression, if true, prevents the Transport from
requesting compression with an "Accept-Encoding: gzip"
request header when the Request contains no existing
Accept-Encoding value. If the Transport requests gzip on
its own and gets a gzipped response, it's transparently
decoded in the Response.Body. However, if the user
explicitly requested gzip it is not automatically
uncompressed.
MaxDecoderHeaderTableSize optionally specifies the http2
SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
informs the remote endpoint of the maximum size of the header compression
table used to decode header blocks, in octets. If zero, the default value
of 4096 is used.
MaxEncoderHeaderTableSize optionally specifies an upper limit for the
header compression table used for encoding request headers. Received
SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
the default value of 4096 is used.
MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
send in the initial settings frame. It is how many bytes
of response headers are allowed. Unlike the http2 spec, zero here
means to use a default limit (currently 10MB). If you actually
want to advertise an unlimited value to the peer, Transport
interprets the highest possible value here (0xffffffff or 1<<32-1)
to mean no limit.
MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
initial settings frame. It is the size in bytes of the largest frame
payload that the sender is willing to receive. If 0, no setting is
sent, and the value is provided by the peer, which should be 16384
according to the spec:
https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
Values are bounded in the range 16k to 16M.
PingTimeout is the timeout after which the connection will be closed
if a response to Ping is not received.
Defaults to 15s.
ReadIdleTimeout is the timeout after which a health check using ping
frame will be carried out if no frame is received on the connection.
Note that a ping response will is considered a received frame, so if
there is no other traffic on the connection, the health check will
be performed every ReadIdleTimeout interval.
If zero, no health check is performed.
StrictMaxConcurrentStreams controls whether the server's
SETTINGS_MAX_CONCURRENT_STREAMS should be respected
globally. If false, new TCP connections are created to the
server as needed to keep each under the per-connection
SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
a global limit and callers of RoundTrip block when needed,
waiting for their turn.
TLSClientConfig specifies the TLS configuration to use with
tls.Client. If nil, the default configuration is used.
WriteByteTimeout is the timeout after which the connection will be
closed no data can be written to it. The timeout begins when data is
available to write, and is extended whenever any bytes are written.
Transport.connPoolOncesync.Once
// non-nil version of ConnPool
t1, if non-nil, is the standard library Transport using
this transport. Its settings are used (but not its
RoundTrip method, etc).
CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle.
It does not interrupt any connections currently in use.
( noDialH2RoundTripper) NewClientConn(c net.Conn) (*ClientConn, error)( noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
RoundTripOpt is like RoundTrip, but takes options.
( noDialH2RoundTripper) connPool() ClientConnPool( noDialH2RoundTripper) dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error)( noDialH2RoundTripper) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error)
dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS
connection.
( noDialH2RoundTripper) disableCompression() bool
disableKeepAlives reports whether connections should be closed as
soon as possible after handling the first request.
( noDialH2RoundTripper) expectContinueTimeout() time.Duration( noDialH2RoundTripper) idleConnTimeout() time.Duration( noDialH2RoundTripper) initConnPool()( noDialH2RoundTripper) logf(format string, args ...interface{})( noDialH2RoundTripper) maxDecoderHeaderTableSize() uint32( noDialH2RoundTripper) maxEncoderHeaderTableSize() uint32( noDialH2RoundTripper) maxFrameReadSize() uint32( noDialH2RoundTripper) maxHeaderListSize() uint32( noDialH2RoundTripper) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error)( noDialH2RoundTripper) newTLSConfig(host string) *tls.Config( noDialH2RoundTripper) pingTimeout() time.Duration( noDialH2RoundTripper) vlogf(format string, args ...interface{})
noDialH2RoundTripper : net/http.RoundTripper
noDialH2RoundTripper : net/http.h2Transport
noDialH2RoundTripper : net/http/httptest.closeIdleTransport
func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error)
outflow is the outbound flow control window's size.
conn points to the shared connection-level outflow that is
shared by all streams on that conn. It is nil for the outflow
that's on the conn directly.
n is the number of DATA bytes we're allowed to send.
An outflow is kept both on a conn and a per-stream.
add adds n bytes (positive or negative) to the flow control window.
It returns false if the sum would exceed 2^31-1.
(*outflow) available() int32(*outflow) setConnFlow(cf *outflow)(*outflow) take(n int32)
pipe is a goroutine-safe io.Reader/io.Writer pair. It's like
io.Pipe except there are no PipeReader/PipeWriter halves, and the
underlying buffer is an interface. (io.Pipe is always unbuffered)
// nil when done reading
// immediate read error (caller doesn't see rest of b)
// c.L lazily initialized to &p.mu
// closed on error
// read error once empty. non-nil means closed.
musync.Mutex
// optional code to run in Read before error
// bytes unread when done
BreakWithError causes the next Read (waking up a current blocked
Read if needed) to return the provided err immediately, without
waiting for unread data.
CloseWithError causes the next Read (waking up a current blocked
Read if needed) to return the provided err after all data has been
read.
The error must be non-nil.
Done returns a channel which is closed if and when this pipe is closed
with CloseWithError.
Err returns the error (if any) first set by BreakWithError or CloseWithError.
(*pipe) Len() int
Read waits until data is available and copies bytes
from the buffer into p.
Write copies bytes from p into the buffer and wakes a reader.
It is an error to write more data than the buffer can hold.
requires p.mu be held.
(*pipe) closeWithError(dst *error, err error, fn func())
closeWithErrorAndCode is like CloseWithError but also sets some code to run
in the caller's goroutine before returning the error.
setBuffer initializes the pipe buffer.
It has no effect if the pipe is already closed.
*pipe : io.Reader
*pipe : io.ReadWriter
*pipe : io.Writer
*pipe : pipeBuffer
*pipe : net/http.http2pipeBuffer
priorityNode is a node in an HTTP/2 priority tree.
Each node is associated with a single stream ID.
See RFC 7540, Section 5.3.
// number of bytes written by this node, or 0 if closed
// id of the stream, or 0 for the root of the tree
// start of the kids list
// doubly-linked list of siblings
These links form the priority tree.
// doubly-linked list of siblings
// queue of pending frames to write
// open | closed | idle
// sum(node.bytes) of all nodes in this subtree
// the actual weight is weight+1, so the value is in [1,256]
(*priorityNode) addBytes(b int64)(*priorityNode) setParent(parent *priorityNode)
walkReadyInOrder iterates over the tree in priority order, calling f for each node
with a non-empty write queue. When f returns true, this function returns true and the
walk halts. tmp is used as scratch space for sorting.
f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true
if any ancestor p of n is still open (ignoring the root node).
lists of nodes that have been closed or are idle, but are kept in
the tree for improved prioritization. When the lengths exceed either
maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.
enableWriteThrottlebool
lists of nodes that have been closed or are idle, but are kept in
the tree for improved prioritization. When the lengths exceed either
maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.
From the config.
maxID is the maximum stream id in nodes.
maxIdleNodesInTreeint
nodes maps stream ids to priority tree nodes.
pool of empty queues for reuse.
root is the root of the priority tree, where root.id = 0.
The root queues control frames that are not associated with any stream.
tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations.
writeThrottleLimitint32(*priorityWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam)(*priorityWriteScheduler) CloseStream(streamID uint32)(*priorityWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions)(*priorityWriteScheduler) Pop() (wr FrameWriteRequest, ok bool)(*priorityWriteScheduler) Push(wr FrameWriteRequest)(*priorityWriteScheduler) addClosedOrIdleNode(list *[]*priorityNode, maxSize int, n *priorityNode)(*priorityWriteScheduler) removeNode(n *priorityNode)
*priorityWriteScheduler : WriteScheduler
pool of empty queues for reuse.
sq contains the stream-specific queues, keyed by stream ID.
When a stream is idle, closed, or emptied, it's deleted
from the map.
zero are frames not associated with a specific stream.
(*randomWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam)(*randomWriteScheduler) CloseStream(streamID uint32)(*randomWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions)(*randomWriteScheduler) Pop() (FrameWriteRequest, bool)(*randomWriteScheduler) Push(wr FrameWriteRequest)
*randomWriteScheduler : WriteScheduler
errerror
// valid until readMore is called
readMore should be called once the consumer no longer needs or
retains f. After readMore, f is invalid and more frames can be
read.
requestBody is the Handler's Request.Body type.
Read and Close may be called concurrently.
// for use by Close only
conn*serverConn
// need to send a 100-continue
// non-nil if we have a HTTP entity message body
// for use by Read only
stream*stream(*requestBody) Close() error(*requestBody) Read(p []byte) (n int, err error)
*requestBody : io.Closer
*requestBody : io.ReadCloser
*requestBody : io.Reader
responseWriter is the http.ResponseWriter implementation. It's
intentionally small (1 pointer wide) to minimize garbage. The
responseWriterState pointer inside is zeroed at the end of a
request (in handlerDone) and calls on the responseWriter thereafter
simply crash (caller's mistake), but the much larger responseWriterState
and buffers are reused between multiple requests.
rws*responseWriterState(*responseWriter) CloseNotify() <-chan bool(*responseWriter) Flush()(*responseWriter) FlushError() error(*responseWriter) Header() http.Header(*responseWriter) Push(target string, opts *http.PushOptions) error(*responseWriter) SetReadDeadline(deadline time.Time) error(*responseWriter) SetWriteDeadline(deadline time.Time) error
The Life Of A Write is like this:
* Handler calls w.Write or w.WriteString ->
* -> rws.bw (*bufio.Writer) ->
* (Handler might call Flush)
* -> chunkWriter{rws}
* -> responseWriterState.writeChunk(p []byte)
* -> responseWriterState.writeChunk (most of the magic; see comment there)
(*responseWriter) WriteHeader(code int)(*responseWriter) WriteString(s string) (n int, err error)(*responseWriter) handlerDone()
either dataB or dataS is non-zero.
*responseWriter : io.StringWriter
*responseWriter : io.Writer
*responseWriter : net/http.CloseNotifier
*responseWriter : net/http.Flusher
*responseWriter : net/http.Pusher
*responseWriter : net/http.ResponseWriter
*responseWriter : stringWriter
*responseWriter : net/http.http2stringWriter
*responseWriter : net/http/httputil.writeFlusher
TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
// writing to a chunkWriter{this *responseWriterState}
// nil until first used
// guards closeNotifierCh
conn*serverConn
// a Write failed; don't reuse this responseWriterState
// handler has finished
mutated by http.Handler goroutine:
// nil until called
req*http.Request
// non-zero if handler set a Content-Length header
// have we sent the header frame?
// snapshot of handlerHeader at WriteHeader time
// status code passed to WriteHeader
immutable within a request:
// set in writeChunk
wroteBytesint64
// WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
declareTrailer is called for each Trailer header when the
response header is written. It notes that a header will need to be
written in the trailers at the end of the response.
(*responseWriterState) hasNonemptyTrailers() bool(*responseWriterState) hasTrailers() bool
promoteUndeclaredTrailers permits http.Handlers to set trailers
after the header has already been flushed. Because the Go
ResponseWriter interface has no way to set Trailers (only the
Header), and because we didn't want to expand the ResponseWriter
interface, and because nobody used trailers, and because RFC 7230
says you SHOULD (but not must) predeclare any trailers in the
header, the official ResponseWriter rules said trailers in Go must
be predeclared, and then we reuse the same ResponseWriter.Header()
map to mean both Headers and Trailers. When it's time to write the
Trailers, we pick out the fields of Headers that were declared as
trailers. That worked for a while, until we found the first major
user of Trailers in the wild: gRPC (using them only over http2),
and gRPC libraries permit setting trailers mid-stream without
predeclaring them. So: change of plans. We still permit the old
way, but we also permit this hack: if a Header() key begins with
"Trailer:", the suffix of that key is a Trailer. Because ':' is an
invalid token byte anyway, there is no ambiguity. (And it's already
filtered out) It's mildly hacky, but not terrible.
This method runs after the Handler is done and promotes any Header
fields to be trailers.
writeChunk writes chunks from the bufio.Writer. But because
bufio.Writer may bypass its chunking, sometimes p may be
arbitrarily large.
writeChunk is also responsible (on the first chunk) for sending the
HEADER response.
(*responseWriterState) writeHeader(code int)
// our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
baseCtxcontext.Context
// from handlers -> serve
// writing to conn
// http2-lower-case -> Go-Canonical-Case
// canonHeader keys size in bytes
// SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
connnet.Conn
// number of open streams initiated by the client
// number of open streams initiated by server push
// closed when serverConn.serve ends
// conn-wide (not stream-specific) outbound flow control
framer*FramergoAwayCodeErrCodehandlerhttp.Handler
Owned by the writeFrameAsync goroutine:
hpackEncoder*hpack.Encoderhs*http.Server
// nil if unused
// whether we're in the scheduleFrameWrite loop
// we've started to or sent GOAWAY
// conn-wide inbound flow control
initialStreamSendWindowSizeint32
// max ever seen from client (odd), or 0 if there have been no client requests
maxFrameSizeint32
// ID of the last push promise (even), or 0 if there have been no pushes
// we need to schedule a GOAWAY frame write
needToSendSettingsAckbool
// last frame write wasn't a flush
// zero means unknown (default)
pushEnabledbool
// control frames in the writeSched queue
// written by serverConn.readFrames
remoteAddrStrstring
// preface has already been read, used in h2c upgrade
// got the initial SETTINGS frame after the preface
Everything following is owned by the serve loop; use serveG.check():
// used to verify funcs are on serve()
// misc messages & code to send to / run on the serve loop
Used by startGracefulShutdown.
// nil until used
Immutable:
streamsmap[uint32]*stream
// shared by all handlers, like net/http
// how many SETTINGS have we sent without ACKs?
// from handlers -> serve
writeSchedWriteScheduler
// started writing a frame (on serve goroutine or separate)
// started a frame on its own goroutine but haven't heard back on wroteFrameCh
// from writeFrameAsync -> serve, tickles more frame writes
(*serverConn) CloseConn() error(*serverConn) Flush() error(*serverConn) Framer() *Framer(*serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)(*serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{})(*serverConn) canonicalHeader(v string) string(*serverConn) checkPriority(streamID uint32, p PriorityParam) error(*serverConn) closeAllStreamsOnConnClose()(*serverConn) closeStream(st *stream, err error)(*serverConn) condlogf(err error, format string, args ...interface{})(*serverConn) countError(name string, err error) error(*serverConn) curOpenStreams() uint32(*serverConn) goAway(code ErrCode)(*serverConn) logf(format string, args ...interface{})(*serverConn) maxHeaderListSize() uint32(*serverConn) newResponseWriter(st *stream, req *http.Request) *responseWriter(*serverConn) newStream(id, pusherID uint32, state streamState) *stream(*serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error)(*serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error)(*serverConn) noteBodyRead(st *stream, n int)
called from handler goroutines.
Notes that the handler for the given stream ID read n bytes of its body
and schedules flow control tokens to be sent.
(*serverConn) notePanic()(*serverConn) onIdleTimer()(*serverConn) onSettingsTimer()(*serverConn) onShutdownTimer()(*serverConn) processData(f *DataFrame) error(*serverConn) processFrame(f Frame) error
processFrameFromReader processes the serve loop's read from readFrameCh from the
frame-reading goroutine.
processFrameFromReader returns whether the connection should be kept open.
(*serverConn) processGoAway(f *GoAwayFrame) error(*serverConn) processHeaders(f *MetaHeadersFrame) error(*serverConn) processPing(f *PingFrame) error(*serverConn) processPriority(f *PriorityFrame) error(*serverConn) processResetStream(f *RSTStreamFrame) error(*serverConn) processSetting(s Setting) error(*serverConn) processSettingInitialWindowSize(val uint32) error(*serverConn) processSettings(f *SettingsFrame) error(*serverConn) processWindowUpdate(f *WindowUpdateFrame) error
readFrames is the loop that reads incoming frames.
It takes care to only read one frame at a time, blocking until the
consumer is done with the frame.
It's run on its own goroutine.
readPreface reads the ClientPreface greeting from the peer or
returns errPrefaceTimeout on timeout, or an error if the greeting
is invalid.
(*serverConn) rejectConn(err ErrCode, debug string)(*serverConn) resetStream(se StreamError)
Run on its own goroutine.
scheduleFrameWrite tickles the frame writing scheduler.
If a frame is already being written, nothing happens. This will be called again
when the frame is done being written.
If a frame isn't being written and we need to send one, the best frame
to send is selected by writeSched.
If a frame isn't being written and there's nothing else to send, we
flush the write buffer.
(*serverConn) sendServeMsg(msg interface{})
st may be nil for conn-level
st may be nil for conn-level
(*serverConn) serve()
setConnState calls the net/http ConnState hook for this connection, if configured.
Note that the net/http package does StateNew and StateClosed for us.
There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
(*serverConn) shutDownIn(d time.Duration)
startFrameWrite starts a goroutine to write wr (in a separate
goroutine since that might block on the network), and updates the
serve goroutine's state about the world, updated from info in wr.
startGracefulShutdown gracefully shuts down a connection. This
sends GOAWAY with ErrCodeNo to tell the client we're gracefully
shutting down. The connection isn't closed until all current
streams are done.
startGracefulShutdown returns immediately; it does not wait until
the connection has shut down.
(*serverConn) startGracefulShutdownInternal()(*serverConn) startPush(msg *startPushRequest)(*serverConn) state(streamID uint32) (streamState, *stream)(*serverConn) stopShutdownTimer()(*serverConn) upgradeRequest(req *http.Request)(*serverConn) vlogf(format string, args ...interface{})
called from handler goroutines.
writeDataFromHandler writes DATA response frames from a handler on
the given stream.
writeFrame schedules a frame to write and sends it if there's nothing
already being written.
There is no pushback here (the serve goroutine never blocks). It's
the http.Handlers that block, waiting for their previous frames to
make it onto the wire
If you're not on the serve goroutine, use writeFrameFromHandler instead.
writeFrameAsync runs in its own goroutine and writes a single frame
and then reports when it's done.
At most one goroutine can be running writeFrameAsync at a time per
serverConn.
writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
if the connection has gone away.
This must not be run from the serve goroutine itself, else it might
deadlock writing to sc.wantWriteFrameCh (which is only mildly
buffered and is read by serve itself). If you're on the serve
goroutine, call writeFrame instead.
called from handler goroutines.
h may be nil.
wroteFrame is called on the serve goroutine with the result of
whatever happened on writeFrameAsync.
*serverConn : writeContext
// owned by sorter
Keys returns the sorted keys of h.
The returned slice is only valid until s used again or returned to
its pool.
(*sorter) Len() int(*sorter) Less(i, j int) bool(*sorter) SortStrings(ss []string)(*sorter) Swap(i, j int)
*sorter : sort.Interface
( sortPriorityNodeSiblings) Len() int( sortPriorityNodeSiblings) Less(i, k int) bool( sortPriorityNodeSiblings) Swap(i, k int)
sortPriorityNodeSiblings : sort.Interface
stream represents a stream. This is the minimal metadata needed by
the serve goroutine. Most of the actual stream state is owned by
the http.Handler's goroutine in the responseWriter. Because the
responseWriter's responseWriterState is recycled at the end of a
handler, this struct intentionally has no pointer to the
*responseWriter{,State} itself, as the Handler ending nils out the
responseWriter's state field.
// non-nil if expecting DATA frames
owned by serverConn's serve loop:
// body bytes seen so far
cancelCtxfunc()
// set before cw is closed
ctxcontext.Context
// closed wait stream transitions to closed state
// or -1 if undeclared
// limits writing from Handler to client
// HEADER frame for trailers was seen
iduint32
// what the client is allowed to POST/etc to us
// nil if unused
// handler's Request.Trailer
// RST_STREAM queued for write; set by sc.resetStream
immutable:
statestreamState
// accumulated trailers
// nil if unused
// whether we wrote headers (not status 100)
copyTrailersToHandlerRequest is run in the Handler's goroutine in
its Request.Body.Read just before it gets io.EOF.
endStream closes a Request.Body's pipe. It is called when a DATA
frame says a request body is over (or after trailers).
isPushed reports whether the stream is server-initiated.
onReadTimeout is run on its own goroutine (from time.AfterFunc)
when the stream's ReadTimeout has fired.
onWriteTimeout is run on its own goroutine (from time.AfterFunc)
when the stream's WriteTimeout has fired.
(*stream) processTrailerHeaders(f *MetaHeadersFrame) error
transportResponseBody is the concrete type of Transport.RoundTrip's
Response.Body. It is an io.ReadCloser.
cs*clientStream( transportResponseBody) Close() error( transportResponseBody) Read(p []byte) (n int, err error)
transportResponseBody : io.Closer
transportResponseBody : io.ReadCloser
transportResponseBody : io.Reader
writeContext is the interface needed by the various frame writer
types below. All the writeFrame methods below are scheduled via the
frame writing scheduler (see writeScheduler in writesched.go).
This interface is implemented by *serverConn.
TODO: decide whether to a) use this in the client code (which didn't
end up using this yet, because it has a simpler design, not
currently implementing priorities), or b) delete this and
make the server code a bit more concrete.
( writeContext) CloseConn() error( writeContext) Flush() error( writeContext) Framer() *Framer
HeaderEncoder returns an HPACK encoder that writes to the
returned buffer.
*serverConn
func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error
func StreamError.writeFrame(ctx writeContext) error
writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames.
Creates an ID for a pushed stream. This runs on serveG just before
the frame is written. The returned ID is copied to promisedID.
hhttp.Header
// for :method
promisedIDuint32
// pusher stream
// for :scheme, :authority, :path
(*writePushPromise) staysWithinBuffer(max int) bool(*writePushPromise) writeFrame(ctx writeContext) error(*writePushPromise) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error
*writePushPromise : writeFramer
writeQueue is used by implementations of WriteScheduler.
s[]FrameWriteRequest
consume consumes up to n bytes from q.s[0]. If the frame is
entirely consumed, it is removed from the queue. If the frame
is partially consumed, the frame is kept with the consumed
bytes removed. Returns true iff any bytes were consumed.
(*writeQueue) empty() bool(*writeQueue) push(wr FrameWriteRequest)(*writeQueue) shift() FrameWriteRequest
get returns an empty writeQueue.
put inserts an unused writeQueue into the pool.
Package-Level Functions (total 91, in which 7 are exported)
ConfigureServer adds HTTP/2 support to a net/http Server.
The configuration conf may be nil.
ConfigureServer must be called before s begins serving.
ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
It returns an error if t1 has already been HTTP/2-enabled.
Use ConfigureTransports instead to configure the HTTP/2 Transport.
ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
It returns a new HTTP/2 Transport for further configuration.
It returns an error if t1 has already been HTTP/2-enabled.
NewFramer returns a Framer that writes frames to w and reads them from r.
NewPriorityWriteScheduler constructs a WriteScheduler that schedules
frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3.
If cfg is nil, default options are used.
NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2
priorities. Control frames like SETTINGS and PING are written before DATA
frames, but if no control frames are queued and multiple streams have queued
HEADERS or DATA frames, Pop selects a ready stream arbitrarily.
ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
Most users should use Framer.ReadFrame instead.
actualContentLength returns a sanitized version of
req.ContentLength, where 0 actually means zero (not unknown) and -1
means unknown.
asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t
are equal, ASCII-case-insensitively.
asciiToLower returns the lowercase version of s if s is ASCII and printable,
and whether or not it was.
authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
and returns a host:port. The port 443 is added if needed.
checkConnHeaders checks whether req has any invalid connection-level headers.
per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
Certain headers are special-cased as okay but not transmitted later.
checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
per RFC 7540 Section 8.1.2.2.
The returned error is reported to users.
checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.
h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
disabled. See comments on h1ServerShutdownChan above for why
the code is written this way.
isASCIIPrint returns whether s is ASCII and printable according to
https://tools.ietf.org/html/rfc20#section-4.2.
isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
References:
https://tools.ietf.org/html/rfc7540#appendix-A
Reject cipher suites from Appendix A.
"This list includes those cipher suites that do not
offer an ephemeral key exchange and those that are
based on the TLS null, stream or block cipher type"
isClosedConnError reports whether err is an error from use of a closed
network connection.
isConnectionCloseRequest reports whether req should use its own
connection for a single request and then close the connection.
isNoCachedConnError reports whether err is of type noCachedConnError
or its equivalent renamed type in net/http2's h2_bundle.go. Both types
may coexist in the same running program.
shouldRetryDial reports whether the current request should
retry dialing after the call finished unsuccessfully, for example
if the dial was canceled because of a context cancellation or
deadline expiry.
shouldRetryRequest is called by RoundTrip when a request fails to get
response headers. It is always called with a non-nil error.
It returns either a request to retry (either the same request, or a
modified clone), or an error if the request can't be replayed.
shouldSendReqContentLength reports whether the http2.Transport should send
a "content-length" request header. This logic is basically a copy of the net/http
transferWriter.shouldSendContentLength.
The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
-1 means unknown.
splitHeaderBlock splits headerBlock into fragments so that each fragment fits
in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
for the first/last fragment, respectively.
takeInflows attempts to take n bytes from two inflows,
typically connection-level and stream-level flows.
It reports whether both windows have available capacity.
terminalReadFrameError reports whether err is an unrecoverable
error from ReadFrame and no other frames should be read.
validPseudoPath reports whether v is a valid :path pseudo-header
value. It must be either:
- a non-empty string starting with '/'
- the string '*', for OPTIONS requests.
For now this is only used a quick check for deciding when to clean
up Opaque URLs before sending requests from the Transport.
See golang.org/issue/16847
We used to enforce that the path also didn't start with "//", but
Google's GFE accepts such paths and Chrome sends them, so ignore
that part of the spec. See golang.org/issue/19103.
validWireHeaderFieldName reports whether v is a valid header field
name (key). See httpguts.ValidHeaderName for the base rules.
Further, http2 says:
"Just as in HTTP/1.x, header field names are strings of ASCII
characters that are compared in a case-insensitive
fashion. However, header field names MUST be converted to
lowercase prior to their encoding in HTTP/2. "
writeEndsStream reports whether w writes a frame that will transition
the stream to a half-closed local state. This returns false for RST_STREAM,
which closes the entire stream (not just the local half).
Package-Level Variables (total 72, in which 6 are exported)
From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
Buffer chunks are allocated from a pool to reduce pressure on GC.
The maximum wasted space per dataBuffer is 2x the largest size class,
which happens when the dataBuffer has multiple chunks and there is
one unread byte in both the first and last chunks. We use a few size
classes to minimize overheads for servers that typically receive very
small request bodies.
TODO: Benchmark to determine if the pools are necessary. The GC may have
improved enough that we can instead allocate chunks like this:
make([]byte, max(16<<10, expectedBytesRemaining))
Buffer chunks are allocated from a pool to reduce pressure on GC.
The maximum wasted space per dataBuffer is 2x the largest size class,
which happens when the dataBuffer has multiple chunks and there is
one unread byte in both the first and last chunks. We use a few size
classes to minimize overheads for servers that typically receive very
small request bodies.
TODO: Benchmark to determine if the pools are necessary. The GC may have
improved enough that we can instead allocate chunks like this:
make([]byte, max(16<<10, expectedBytesRemaining))
errFromPeer is a sentinel error value for StreamError.Cause to
indicate that the StreamError was sent from the peer over the wire
and wasn't locally generated in the Transport.
errHandlerPanicked is the error given to any callers blocked in a read from
Request.Body when the main goroutine panics. Since most handlers read in the
main ServeHTTP goroutine, this will show up rarely.
After sending GOAWAY with an error code (non-graceful shutdown), the
connection will close after goAwayTimeout.
If we close the connection immediately after sending GOAWAY, there may
be unsent data in our kernel receive buffer, which will cause the kernel
to send a TCP RST on close() instead of a FIN. This RST will abort the
connection immediately, whether or not the client had received the GOAWAY.
Ideally we should delay for at least 1 RTT + epsilon so the client has
a chance to read the GOAWAY and stop sending messages. Measuring RTT
is hard, so we approximate with 1 second. See golang.org/issue/18701.
This is a var so it can be shorter in tests, where all requests uses the
loopback interface making the expected RTT very small.
TODO: configurable?
TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
that, if present, signals that the map entry is actually for
the response trailers, and not the response headers. The prefix
is stripped after the ServeHTTP call finishes and the values are
sent in the trailers.
This mechanism is intended only for trailers that are not known
prior to the headers being written. If the set of trailers is fixed
or known before the header is written, the normal Go trailers mechanism
is preferred:
https://golang.org/pkg/net/http/#ResponseWriter
https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
bufWriterPoolBufferSize is the size of bufio.Writer's
buffers created using bufWriterPool.
TODO: pick a less arbitrary value? this is a bit under
(3 x typical 1500 byte MTU) at least. Other than that,
not much thought went into it.
initialMaxConcurrentStreams is a connections maxConcurrentStreams until
it's received servers initial SETTINGS frame, which corresponds with the
spec's minimum recommended value.
maxCachedCanonicalHeadersKeysSize is an arbitrarily-chosen limit on the size
of the entries in the canonHeader cache.
This should be larger than the size of unique, uncommon header keys likely to
be sent by the peer, while not so high as to permit unreasonable memory usage
if the peer sends an unbounded number of unique header keys.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
transportDefaultConnFlow is how many connection-level flow control
tokens we give the server at start-up, past the default 64k.
transportDefaultStreamFlow is how many stream-level flow
control tokens we announce to the peer, and how many bytes
we buffer per stream.
The pages are generated with Goldsv0.4.9. (GOOS=linux GOARCH=amd64)