Movatterモバイル変換


[0]ホーム

URL:


transport

package
v1.77.0Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2025 License:Apache-2.0Imports:48Imported by:0

Details

Repository

github.com/grpc/grpc-go

Links

Documentation

Overview

Package transport defines and implements message oriented communicationchannel to complete various transactions (e.g., an RPC). It is meant forgrpc-internal usage and is not intended to be imported directly by users.

Index

Constants

This section is empty.

Variables

View Source
var (// ErrIllegalHeaderWrite indicates that setting header is illegal because of// the stream's state.ErrIllegalHeaderWrite =status.Error(codes.Internal, "transport: SendHeader called multiple times")// ErrHeaderListSizeLimitViolation indicates that the header list size is larger// than the limit set by peer.ErrHeaderListSizeLimitViolation =status.Error(codes.Internal, "transport: trying to send header list size larger than the limit set by peer"))
View Source
var (// ErrConnClosing indicates that the transport is closing.ErrConnClosing = connectionErrorf(true,nil, "transport is closing"))
View Source
var MaxStreamID =uint32(math.MaxInt32 * 3 / 4)

MaxStreamID is the upper bound for the stream ID before the currenttransport gracefully closes and new transport is created for subsequent RPCs.This is set to 75% of 2^31-1. Streams are identified with an unsigned 31-bitinteger. It's exported so that tests can override it.

Functions

funcContextErr

func ContextErr(errerror)error

ContextErr converts the error from context package into a status error.

funcGetConnectionadded inv1.41.0

func GetConnection(ctxcontext.Context)net.Conn

GetConnection gets the connection from the context.

funcParseDialTargetadded inv1.71.2

func ParseDialTarget(targetstring) (string,string)

ParseDialTarget returns the network and address to pass to dialer.

funcSetConnectionadded inv1.60.0

func SetConnection(ctxcontext.Context, connnet.Conn)context.Context

SetConnection adds the connection to the context to be able to getinformation about the destination ip and port for an incoming RPC. This alsoallows any unary or streaming interceptors to see the connection.

Types

typeCallHdr

type CallHdr struct {// Host specifies the peer's host.Hoststring// Method specifies the operation to perform.Methodstring// SendCompress specifies the compression algorithm applied on// outbound message.SendCompressstring// Creds specifies credentials.PerRPCCredentials for a call.Credscredentials.PerRPCCredentials// ContentSubtype specifies the content-subtype for a request. For example, a// content-subtype of "proto" will result in a content-type of// "application/grpc+proto". The value of ContentSubtype must be all// lowercase, otherwise the behavior is undefined. See//https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests// for more details.ContentSubtypestringPreviousAttemptsint// value of grpc-previous-rpc-attempts header to setDoneFunc func()// called when the stream is finished// Authority is used to explicitly override the `:authority` header. If set,// this value takes precedence over the Host field and will be used as the// value for the `:authority` header.Authoritystring}

CallHdr carries the information of a particular RPC.

typeClientStreamadded inv1.69.0

type ClientStream struct {Stream// Embed for common stream functionality.// contains filtered or unexported fields}

ClientStream implements streaming functionality for a gRPC client.

func (*ClientStream)BytesReceivedadded inv1.69.0

func (s *ClientStream) BytesReceived()bool

BytesReceived indicates whether any bytes have been received on this stream.

func (*ClientStream)Closeadded inv1.69.0

func (s *ClientStream) Close(errerror)

Close closes the stream and propagates err to any readers.

func (*ClientStream)Doneadded inv1.69.0

func (s *ClientStream) Done() <-chan struct{}

Done returns a channel which is closed when it receives the final statusfrom the server.

func (*ClientStream)Headeradded inv1.69.0

func (s *ClientStream) Header() (metadata.MD,error)

Header returns the header metadata of the stream. Acquires the key-valuepairs of header metadata once it is available. It blocks until i) themetadata is ready or ii) there is no header metadata or iii) the stream iscanceled/expired.

func (*ClientStream)Readadded inv1.69.0

func (s *ClientStream) Read(nint) (mem.BufferSlice,error)

Read reads an n byte message from the input stream.

func (*ClientStream)RecvCompressadded inv1.69.0

func (s *ClientStream) RecvCompress()string

RecvCompress returns the compression algorithm applied to the inboundmessage. It is empty string if there is no compression applied.

func (*ClientStream)Statusadded inv1.69.0

func (s *ClientStream) Status() *status.Status

Status returns the status received from the server.Status can be read safely only after the stream has ended,that is, after Done() is closed.

func (*ClientStream)TrailersOnlyadded inv1.69.0

func (s *ClientStream) TrailersOnly()bool

TrailersOnly blocks until a header or trailers-only frame is received andthen returns true if the stream was trailers-only. If the stream endsbefore headers are received, returns true, nil.

func (*ClientStream)Unprocessedadded inv1.69.0

func (s *ClientStream) Unprocessed()bool

Unprocessed indicates whether the server did not process this stream --i.e. it sent a refused stream or GOAWAY including this stream ID.

func (*ClientStream)Writeadded inv1.69.0

func (s *ClientStream) Write(hdr []byte, datamem.BufferSlice, opts *WriteOptions)error

Write writes the hdr and data bytes to the output stream.

typeClientTransport

type ClientTransport interface {// Close tears down this transport. Once it returns, the transport// should not be accessed any more. The caller must make sure this// is called only once.Close(errerror)// GracefulClose starts to tear down the transport: the transport will stop// accepting new RPCs and NewStream will return error. Once all streams are// finished, the transport will close.//// It does not block.GracefulClose()// NewStream creates a Stream for an RPC.NewStream(ctxcontext.Context, callHdr *CallHdr) (*ClientStream,error)// Error returns a channel that is closed when some I/O error// happens. Typically the caller should have a goroutine to monitor// this in order to take action (e.g., close the current transport// and create a new one) in error case. It should not return nil// once the transport is initiated.Error() <-chan struct{}// GoAway returns a channel that is closed when ClientTransport// receives the draining signal from the server (e.g., GOAWAY frame in// HTTP/2).GoAway() <-chan struct{}// GetGoAwayReason returns the reason why GoAway frame was received, along// with a human readable string with debug info.GetGoAwayReason() (GoAwayReason,string)// RemoteAddr returns the remote network address.RemoteAddr()net.Addr}

ClientTransport is the common interface for all gRPC client-side transportimplementations.

funcNewHTTP2Clientadded inv1.69.0

func NewHTTP2Client(connectCtx, ctxcontext.Context, addrresolver.Address, optsConnectOptions, onClose func(GoAwayReason)) (_ClientTransport, errerror)

NewHTTP2Client constructs a connected ClientTransport to addr based on HTTP2and starts to receive messages on it. Non-nil error returns if constructionfails.

typeConnectOptions

type ConnectOptions struct {// UserAgent is the application user agent.UserAgentstring// Dialer specifies how to dial a network address.Dialer func(context.Context,string) (net.Conn,error)// FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors.FailOnNonTempDialErrorbool// PerRPCCredentials stores the PerRPCCredentials required to issue RPCs.PerRPCCredentials []credentials.PerRPCCredentials// TransportCredentials stores the Authenticator required to setup a client// connection. Only one of TransportCredentials and CredsBundle is non-nil.TransportCredentialscredentials.TransportCredentials// CredsBundle is the credentials bundle to be used. Only one of// TransportCredentials and CredsBundle is non-nil.CredsBundlecredentials.Bundle// KeepaliveParams stores the keepalive parameters.KeepaliveParamskeepalive.ClientParameters// StatsHandlers stores the handler for stats.StatsHandlers []stats.Handler// InitialWindowSize sets the initial window size for a stream.InitialWindowSizeint32// InitialConnWindowSize sets the initial window size for a connection.InitialConnWindowSizeint32// WriteBufferSize sets the size of write buffer which in turn determines how much data can be batched before it's written on the wire.WriteBufferSizeint// ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall.ReadBufferSizeint// SharedWriteBuffer indicates whether connections should reuse write bufferSharedWriteBufferbool// ChannelzParent sets the addrConn id which initiated the creation of this client transport.ChannelzParent *channelz.SubChannel// MaxHeaderListSize sets the max (uncompressed) size of header list that is prepared to be received.MaxHeaderListSize *uint32// The mem.BufferPool to use when reading/writing to the wire.BufferPoolmem.BufferPool// StaticWindowSize controls whether dynamic window sizing is enabled.StaticWindowSizebool}

ConnectOptions covers all relevant options for communicating with the server.

typeConnectionError

type ConnectionError struct {Descstring// contains filtered or unexported fields}

ConnectionError is an error that results in the termination of theentire connection and the retry of all the active streams.

func (ConnectionError)Error

func (eConnectionError) Error()string

func (ConnectionError)Origin

func (eConnectionError) Origin()error

Origin returns the original error of this connection error.

func (ConnectionError)Temporary

func (eConnectionError) Temporary()bool

Temporary indicates if this connection error is temporary or fatal.

func (ConnectionError)Unwrapadded inv1.45.0

func (eConnectionError) Unwrap()error

Unwrap returns the original error of this connection error or nil when theorigin is nil.

typeGoAwayReason

type GoAwayReasonuint8

GoAwayReason contains the reason for the GoAway frame received.

const (// GoAwayInvalid indicates that no GoAway frame is received.GoAwayInvalidGoAwayReason = 0// GoAwayNoReason is the default value when GoAway frame is received.GoAwayNoReasonGoAwayReason = 1// GoAwayTooManyPings indicates that a GoAway frame with// ErrCodeEnhanceYourCalm was received and that the debug data said// "too_many_pings".GoAwayTooManyPingsGoAwayReason = 2)

typeNewStreamErroradded inv1.40.0

type NewStreamError struct {ErrerrorAllowTransparentRetrybool}

NewStreamError wraps an error and reports additional information. TypicallyNewStream errors result in transparent retry, as they mean nothing went ontothe wire. However, there are two notable exceptions:

  1. If the stream headers violate the max header list size allowed by theserver. It's possible this could succeed on another transport, even ifit's unlikely, but do not transparently retry.
  2. If the credentials errored when requesting their headers. In this case,it's possible a retry can fix the problem, but indefinitely transparentlyretrying is not appropriate as it is likely the credentials, if they caneventually succeed, would need I/O to do so.

func (NewStreamError)Erroradded inv1.40.0

func (eNewStreamError) Error()string

typeServerConfig

type ServerConfig struct {MaxStreamsuint32ConnectionTimeouttime.DurationCredentialscredentials.TransportCredentialsInTapHandletap.ServerInHandleStatsHandlerstats.HandlerKeepaliveParamskeepalive.ServerParametersKeepalivePolicykeepalive.EnforcementPolicyInitialWindowSizeint32InitialConnWindowSizeint32WriteBufferSizeintReadBufferSizeintSharedWriteBufferboolChannelzParent        *channelz.ServerMaxHeaderListSize     *uint32HeaderTableSize       *uint32BufferPoolmem.BufferPoolStaticWindowSizebool}

ServerConfig consists of all the configurations to establish a server transport.

typeServerStreamadded inv1.69.0

type ServerStream struct {Stream// Embed for common stream functionality.// contains filtered or unexported fields}

ServerStream implements streaming functionality for a gRPC server.

func (*ServerStream)ClientAdvertisedCompressorsadded inv1.69.0

func (s *ServerStream) ClientAdvertisedCompressors() []string

ClientAdvertisedCompressors returns the compressor names advertised by theclient via grpc-accept-encoding header.

func (*ServerStream)ContentSubtypeadded inv1.69.0

func (s *ServerStream) ContentSubtype()string

ContentSubtype returns the content-subtype for a request. For example, acontent-subtype of "proto" will result in a content-type of"application/grpc+proto". This will always be lowercase. Seehttps://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests formore details.

func (*ServerStream)Headeradded inv1.69.0

func (s *ServerStream) Header() (metadata.MD,error)

Header returns the header metadata of the stream. It returns the out headerafter t.WriteHeader is called. It does not block and must not be calleduntil after WriteHeader.

func (*ServerStream)HeaderWireLengthadded inv1.69.0

func (s *ServerStream) HeaderWireLength()int

HeaderWireLength returns the size of the headers of the stream as receivedfrom the wire.

func (*ServerStream)Readadded inv1.69.0

func (s *ServerStream) Read(nint) (mem.BufferSlice,error)

Read reads an n byte message from the input stream.

func (*ServerStream)RecvCompressadded inv1.69.0

func (s *ServerStream) RecvCompress()string

RecvCompress returns the compression algorithm applied to the inboundmessage. It is empty string if there is no compression applied.

func (*ServerStream)SendCompressadded inv1.69.0

func (s *ServerStream) SendCompress()string

SendCompress returns the send compressor name.

func (*ServerStream)SendHeaderadded inv1.69.0

func (s *ServerStream) SendHeader(mdmetadata.MD)error

SendHeader sends the header metadata for the given stream.

func (*ServerStream)SetContextadded inv1.69.0

func (s *ServerStream) SetContext(ctxcontext.Context)

SetContext sets the context of the stream. This will be deleted once thestats handler callouts all move to gRPC layer.

func (*ServerStream)SetHeaderadded inv1.69.0

func (s *ServerStream) SetHeader(mdmetadata.MD)error

SetHeader sets the header metadata. This can be called multiple times.This should not be called in parallel to other data writes.

func (*ServerStream)SetSendCompressadded inv1.69.0

func (s *ServerStream) SetSendCompress(namestring)error

SetSendCompress sets the compression algorithm to the stream.

func (*ServerStream)SetTraileradded inv1.69.0

func (s *ServerStream) SetTrailer(mdmetadata.MD)error

SetTrailer sets the trailer metadata which will be sent with the RPC statusby the server. This can be called multiple times.This should not be called parallel to other data writes.

func (*ServerStream)Writeadded inv1.69.0

func (s *ServerStream) Write(hdr []byte, datamem.BufferSlice, opts *WriteOptions)error

Write writes the hdr and data bytes to the output stream.

func (*ServerStream)WriteStatusadded inv1.69.0

func (s *ServerStream) WriteStatus(st *status.Status)error

WriteStatus sends the status of a stream to the client. WriteStatus isthe final call made on a stream and always occurs.

typeServerTransport

type ServerTransport interface {// HandleStreams receives incoming streams using the given handler.HandleStreams(context.Context, func(*ServerStream))// Close tears down the transport. Once it is called, the transport// should not be accessed any more. All the pending streams and their// handlers will be terminated asynchronously.Close(errerror)// Peer returns the peer of the server transport.Peer() *peer.Peer// Drain notifies the client this ServerTransport stops accepting new RPCs.Drain(debugDatastring)}

ServerTransport is the common interface for all gRPC server-side transportimplementations.

Methods may be called concurrently from multiple goroutines, butWrite methods for a given Stream will be called serially.

funcNewServerHandlerTransport

func NewServerHandlerTransport(whttp.ResponseWriter, r *http.Request, statsstats.Handler, bufferPoolmem.BufferPool) (ServerTransport,error)

NewServerHandlerTransport returns a ServerTransport handling gRPC frominside an http.Handler, or writes an HTTP error to w and returns an error.It requires that the http Server supports HTTP/2.

funcNewServerTransport

func NewServerTransport(connnet.Conn, config *ServerConfig) (_ServerTransport, errerror)

NewServerTransport creates a http2 transport with conn and configurationoptions from config.

It returns a non-nil transport and a nil error on success. On failure, itreturns a nil transport and a non-nil error. For a special case where theunderlying conn gets closed before the client preface could be read, itreturns a nil transport and a nil error.

typeStream

type Stream struct {// contains filtered or unexported fields}

Stream represents an RPC in the transport layer.

func (*Stream)Context

func (s *Stream) Context()context.Context

Context returns the context of the stream.

func (*Stream)GoString

func (s *Stream) GoString()string

GoString is implemented by Stream so context.String() won'trace when printing %#v.

func (*Stream)Method

func (s *Stream) Method()string

Method returns the method for the stream.

func (*Stream)ReadMessageHeaderadded inv1.69.0

func (s *Stream) ReadMessageHeader(header []byte) (errerror)

ReadMessageHeader reads data into the provided header slice from the stream.It first checks if there was an error during a previous read operation andreturns it if present. It then requests a read operation for the length ofthe header. It continues to read from the stream until the entire headerslice is filled or an error occurs. If an `io.EOF` error is encountered withpartially read data, it is converted to `io.ErrUnexpectedEOF` to indicate anunexpected end of the stream. The method returns any error encountered duringthe read process or nil if the header was successfully read.

func (*Stream)Trailer

func (s *Stream) Trailer()metadata.MD

Trailer returns the cached trailer metadata. Note that if it is not calledafter the entire stream is done, it could return an empty MD.It can be safely read only after stream has ended that is either reador write have returned io.EOF.

typeWriteOptionsadded inv1.69.0

type WriteOptions struct {// Last indicates whether this write is the last piece for// this stream.Lastbool}

WriteOptions provides additional hints and information for messagetransmission.

Source Files

View all Source files

Directories

PathSynopsis
Package grpchttp2 defines HTTP/2 types and a framer API and implementation.
Package grpchttp2 defines HTTP/2 types and a framer API and implementation.
Package networktype declares the network type to be used in the default dialer.
Package networktype declares the network type to be used in the default dialer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp