transport.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package transport defines and implements message oriented communication
  19. // channel to complete various transactions (e.g., an RPC). It is meant for
  20. // grpc-internal usage and is not intended to be imported directly by users.
  21. package transport // externally used as import "google.golang.org/grpc/transport"
  22. import (
  23. "errors"
  24. "fmt"
  25. "io"
  26. "net"
  27. "sync"
  28. "sync/atomic"
  29. "golang.org/x/net/context"
  30. "google.golang.org/grpc/codes"
  31. "google.golang.org/grpc/credentials"
  32. "google.golang.org/grpc/keepalive"
  33. "google.golang.org/grpc/metadata"
  34. "google.golang.org/grpc/stats"
  35. "google.golang.org/grpc/status"
  36. "google.golang.org/grpc/tap"
  37. )
  38. // recvMsg represents the received msg from the transport. All transport
  39. // protocol specific info has been removed.
  40. type recvMsg struct {
  41. data []byte
  42. // nil: received some data
  43. // io.EOF: stream is completed. data is nil.
  44. // other non-nil error: transport failure. data is nil.
  45. err error
  46. }
  47. // recvBuffer is an unbounded channel of recvMsg structs.
  48. // Note recvBuffer differs from controlBuffer only in that recvBuffer
  49. // holds a channel of only recvMsg structs instead of objects implementing "item" interface.
  50. // recvBuffer is written to much more often than
  51. // controlBuffer and using strict recvMsg structs helps avoid allocation in "recvBuffer.put"
  52. type recvBuffer struct {
  53. c chan recvMsg
  54. mu sync.Mutex
  55. backlog []recvMsg
  56. err error
  57. }
  58. func newRecvBuffer() *recvBuffer {
  59. b := &recvBuffer{
  60. c: make(chan recvMsg, 1),
  61. }
  62. return b
  63. }
  64. func (b *recvBuffer) put(r recvMsg) {
  65. b.mu.Lock()
  66. if b.err != nil {
  67. b.mu.Unlock()
  68. // An error had occurred earlier, don't accept more
  69. // data or errors.
  70. return
  71. }
  72. b.err = r.err
  73. if len(b.backlog) == 0 {
  74. select {
  75. case b.c <- r:
  76. b.mu.Unlock()
  77. return
  78. default:
  79. }
  80. }
  81. b.backlog = append(b.backlog, r)
  82. b.mu.Unlock()
  83. }
  84. func (b *recvBuffer) load() {
  85. b.mu.Lock()
  86. if len(b.backlog) > 0 {
  87. select {
  88. case b.c <- b.backlog[0]:
  89. b.backlog[0] = recvMsg{}
  90. b.backlog = b.backlog[1:]
  91. default:
  92. }
  93. }
  94. b.mu.Unlock()
  95. }
  96. // get returns the channel that receives a recvMsg in the buffer.
  97. //
  98. // Upon receipt of a recvMsg, the caller should call load to send another
  99. // recvMsg onto the channel if there is any.
  100. func (b *recvBuffer) get() <-chan recvMsg {
  101. return b.c
  102. }
  103. //
  104. // recvBufferReader implements io.Reader interface to read the data from
  105. // recvBuffer.
  106. type recvBufferReader struct {
  107. ctx context.Context
  108. ctxDone <-chan struct{} // cache of ctx.Done() (for performance).
  109. recv *recvBuffer
  110. last []byte // Stores the remaining data in the previous calls.
  111. err error
  112. }
  113. // Read reads the next len(p) bytes from last. If last is drained, it tries to
  114. // read additional data from recv. It blocks if there no additional data available
  115. // in recv. If Read returns any non-nil error, it will continue to return that error.
  116. func (r *recvBufferReader) Read(p []byte) (n int, err error) {
  117. if r.err != nil {
  118. return 0, r.err
  119. }
  120. n, r.err = r.read(p)
  121. return n, r.err
  122. }
  123. func (r *recvBufferReader) read(p []byte) (n int, err error) {
  124. if r.last != nil && len(r.last) > 0 {
  125. // Read remaining data left in last call.
  126. copied := copy(p, r.last)
  127. r.last = r.last[copied:]
  128. return copied, nil
  129. }
  130. select {
  131. case <-r.ctxDone:
  132. return 0, ContextErr(r.ctx.Err())
  133. case m := <-r.recv.get():
  134. r.recv.load()
  135. if m.err != nil {
  136. return 0, m.err
  137. }
  138. copied := copy(p, m.data)
  139. r.last = m.data[copied:]
  140. return copied, nil
  141. }
  142. }
  143. type streamState uint32
  144. const (
  145. streamActive streamState = iota
  146. streamWriteDone // EndStream sent
  147. streamReadDone // EndStream received
  148. streamDone // the entire stream is finished.
  149. )
  150. // Stream represents an RPC in the transport layer.
  151. type Stream struct {
  152. id uint32
  153. st ServerTransport // nil for client side Stream
  154. ctx context.Context // the associated context of the stream
  155. cancel context.CancelFunc // always nil for client side Stream
  156. done chan struct{} // closed at the end of stream to unblock writers. On the client side.
  157. ctxDone <-chan struct{} // same as done chan but for server side. Cache of ctx.Done() (for performance)
  158. method string // the associated RPC method of the stream
  159. recvCompress string
  160. sendCompress string
  161. buf *recvBuffer
  162. trReader io.Reader
  163. fc *inFlow
  164. recvQuota uint32
  165. wq *writeQuota
  166. // Callback to state application's intentions to read data. This
  167. // is used to adjust flow control, if needed.
  168. requestRead func(int)
  169. headerChan chan struct{} // closed to indicate the end of header metadata.
  170. headerDone uint32 // set when headerChan is closed. Used to avoid closing headerChan multiple times.
  171. // hdrMu protects header and trailer metadata on the server-side.
  172. hdrMu sync.Mutex
  173. header metadata.MD // the received header metadata.
  174. trailer metadata.MD // the key-value map of trailer metadata.
  175. // On the server-side, headerSent is atomically set to 1 when the headers are sent out.
  176. headerSent uint32
  177. state streamState
  178. // On client-side it is the status error received from the server.
  179. // On server-side it is unused.
  180. status *status.Status
  181. bytesReceived uint32 // indicates whether any bytes have been received on this stream
  182. unprocessed uint32 // set if the server sends a refused stream or GOAWAY including this stream
  183. // contentSubtype is the content-subtype for requests.
  184. // this must be lowercase or the behavior is undefined.
  185. contentSubtype string
  186. }
  187. // isHeaderSent is only valid on the server-side.
  188. func (s *Stream) isHeaderSent() bool {
  189. return atomic.LoadUint32(&s.headerSent) == 1
  190. }
  191. // updateHeaderSent updates headerSent and returns true
  192. // if it was alreay set. It is valid only on server-side.
  193. func (s *Stream) updateHeaderSent() bool {
  194. return atomic.SwapUint32(&s.headerSent, 1) == 1
  195. }
  196. func (s *Stream) swapState(st streamState) streamState {
  197. return streamState(atomic.SwapUint32((*uint32)(&s.state), uint32(st)))
  198. }
  199. func (s *Stream) compareAndSwapState(oldState, newState streamState) bool {
  200. return atomic.CompareAndSwapUint32((*uint32)(&s.state), uint32(oldState), uint32(newState))
  201. }
  202. func (s *Stream) getState() streamState {
  203. return streamState(atomic.LoadUint32((*uint32)(&s.state)))
  204. }
  205. func (s *Stream) waitOnHeader() error {
  206. if s.headerChan == nil {
  207. // On the server headerChan is always nil since a stream originates
  208. // only after having received headers.
  209. return nil
  210. }
  211. select {
  212. case <-s.ctx.Done():
  213. return ContextErr(s.ctx.Err())
  214. case <-s.headerChan:
  215. return nil
  216. }
  217. }
  218. // RecvCompress returns the compression algorithm applied to the inbound
  219. // message. It is empty string if there is no compression applied.
  220. func (s *Stream) RecvCompress() string {
  221. if err := s.waitOnHeader(); err != nil {
  222. return ""
  223. }
  224. return s.recvCompress
  225. }
  226. // SetSendCompress sets the compression algorithm to the stream.
  227. func (s *Stream) SetSendCompress(str string) {
  228. s.sendCompress = str
  229. }
  230. // Done returns a chanel which is closed when it receives the final status
  231. // from the server.
  232. func (s *Stream) Done() <-chan struct{} {
  233. return s.done
  234. }
  235. // Header acquires the key-value pairs of header metadata once it
  236. // is available. It blocks until i) the metadata is ready or ii) there is no
  237. // header metadata or iii) the stream is canceled/expired.
  238. func (s *Stream) Header() (metadata.MD, error) {
  239. err := s.waitOnHeader()
  240. // Even if the stream is closed, header is returned if available.
  241. select {
  242. case <-s.headerChan:
  243. if s.header == nil {
  244. return nil, nil
  245. }
  246. return s.header.Copy(), nil
  247. default:
  248. }
  249. return nil, err
  250. }
  251. // Trailer returns the cached trailer metedata. Note that if it is not called
  252. // after the entire stream is done, it could return an empty MD. Client
  253. // side only.
  254. // It can be safely read only after stream has ended that is either read
  255. // or write have returned io.EOF.
  256. func (s *Stream) Trailer() metadata.MD {
  257. c := s.trailer.Copy()
  258. return c
  259. }
  260. // ServerTransport returns the underlying ServerTransport for the stream.
  261. // The client side stream always returns nil.
  262. func (s *Stream) ServerTransport() ServerTransport {
  263. return s.st
  264. }
  265. // ContentSubtype returns the content-subtype for a request. For example, a
  266. // content-subtype of "proto" will result in a content-type of
  267. // "application/grpc+proto". This will always be lowercase. See
  268. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  269. // more details.
  270. func (s *Stream) ContentSubtype() string {
  271. return s.contentSubtype
  272. }
  273. // Context returns the context of the stream.
  274. func (s *Stream) Context() context.Context {
  275. return s.ctx
  276. }
  277. // Method returns the method for the stream.
  278. func (s *Stream) Method() string {
  279. return s.method
  280. }
  281. // Status returns the status received from the server.
  282. // Status can be read safely only after the stream has ended,
  283. // that is, read or write has returned io.EOF.
  284. func (s *Stream) Status() *status.Status {
  285. return s.status
  286. }
  287. // SetHeader sets the header metadata. This can be called multiple times.
  288. // Server side only.
  289. // This should not be called in parallel to other data writes.
  290. func (s *Stream) SetHeader(md metadata.MD) error {
  291. if md.Len() == 0 {
  292. return nil
  293. }
  294. if s.isHeaderSent() || s.getState() == streamDone {
  295. return ErrIllegalHeaderWrite
  296. }
  297. s.hdrMu.Lock()
  298. s.header = metadata.Join(s.header, md)
  299. s.hdrMu.Unlock()
  300. return nil
  301. }
  302. // SendHeader sends the given header metadata. The given metadata is
  303. // combined with any metadata set by previous calls to SetHeader and
  304. // then written to the transport stream.
  305. func (s *Stream) SendHeader(md metadata.MD) error {
  306. t := s.ServerTransport()
  307. return t.WriteHeader(s, md)
  308. }
  309. // SetTrailer sets the trailer metadata which will be sent with the RPC status
  310. // by the server. This can be called multiple times. Server side only.
  311. // This should not be called parallel to other data writes.
  312. func (s *Stream) SetTrailer(md metadata.MD) error {
  313. if md.Len() == 0 {
  314. return nil
  315. }
  316. if s.getState() == streamDone {
  317. return ErrIllegalHeaderWrite
  318. }
  319. s.hdrMu.Lock()
  320. s.trailer = metadata.Join(s.trailer, md)
  321. s.hdrMu.Unlock()
  322. return nil
  323. }
  324. func (s *Stream) write(m recvMsg) {
  325. s.buf.put(m)
  326. }
  327. // Read reads all p bytes from the wire for this stream.
  328. func (s *Stream) Read(p []byte) (n int, err error) {
  329. // Don't request a read if there was an error earlier
  330. if er := s.trReader.(*transportReader).er; er != nil {
  331. return 0, er
  332. }
  333. s.requestRead(len(p))
  334. return io.ReadFull(s.trReader, p)
  335. }
  336. // tranportReader reads all the data available for this Stream from the transport and
  337. // passes them into the decoder, which converts them into a gRPC message stream.
  338. // The error is io.EOF when the stream is done or another non-nil error if
  339. // the stream broke.
  340. type transportReader struct {
  341. reader io.Reader
  342. // The handler to control the window update procedure for both this
  343. // particular stream and the associated transport.
  344. windowHandler func(int)
  345. er error
  346. }
  347. func (t *transportReader) Read(p []byte) (n int, err error) {
  348. n, err = t.reader.Read(p)
  349. if err != nil {
  350. t.er = err
  351. return
  352. }
  353. t.windowHandler(n)
  354. return
  355. }
  356. // BytesReceived indicates whether any bytes have been received on this stream.
  357. func (s *Stream) BytesReceived() bool {
  358. return atomic.LoadUint32(&s.bytesReceived) == 1
  359. }
  360. // Unprocessed indicates whether the server did not process this stream --
  361. // i.e. it sent a refused stream or GOAWAY including this stream ID.
  362. func (s *Stream) Unprocessed() bool {
  363. return atomic.LoadUint32(&s.unprocessed) == 1
  364. }
  365. // GoString is implemented by Stream so context.String() won't
  366. // race when printing %#v.
  367. func (s *Stream) GoString() string {
  368. return fmt.Sprintf("<stream: %p, %v>", s, s.method)
  369. }
  370. // state of transport
  371. type transportState int
  372. const (
  373. reachable transportState = iota
  374. closing
  375. draining
  376. )
  377. // ServerConfig consists of all the configurations to establish a server transport.
  378. type ServerConfig struct {
  379. MaxStreams uint32
  380. AuthInfo credentials.AuthInfo
  381. InTapHandle tap.ServerInHandle
  382. StatsHandler stats.Handler
  383. KeepaliveParams keepalive.ServerParameters
  384. KeepalivePolicy keepalive.EnforcementPolicy
  385. InitialWindowSize int32
  386. InitialConnWindowSize int32
  387. WriteBufferSize int
  388. ReadBufferSize int
  389. ChannelzParentID int64
  390. }
  391. // NewServerTransport creates a ServerTransport with conn or non-nil error
  392. // if it fails.
  393. func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) {
  394. return newHTTP2Server(conn, config)
  395. }
  396. // ConnectOptions covers all relevant options for communicating with the server.
  397. type ConnectOptions struct {
  398. // UserAgent is the application user agent.
  399. UserAgent string
  400. // Authority is the :authority pseudo-header to use. This field has no effect if
  401. // TransportCredentials is set.
  402. Authority string
  403. // Dialer specifies how to dial a network address.
  404. Dialer func(context.Context, string) (net.Conn, error)
  405. // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors.
  406. FailOnNonTempDialError bool
  407. // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs.
  408. PerRPCCredentials []credentials.PerRPCCredentials
  409. // TransportCredentials stores the Authenticator required to setup a client connection.
  410. TransportCredentials credentials.TransportCredentials
  411. // KeepaliveParams stores the keepalive parameters.
  412. KeepaliveParams keepalive.ClientParameters
  413. // StatsHandler stores the handler for stats.
  414. StatsHandler stats.Handler
  415. // InitialWindowSize sets the initial window size for a stream.
  416. InitialWindowSize int32
  417. // InitialConnWindowSize sets the initial window size for a connection.
  418. InitialConnWindowSize int32
  419. // WriteBufferSize sets the size of write buffer which in turn determines how much data can be batched before it's written on the wire.
  420. WriteBufferSize int
  421. // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall.
  422. ReadBufferSize int
  423. // ChannelzParentID sets the addrConn id which initiate the creation of this client transport.
  424. ChannelzParentID int64
  425. }
  426. // TargetInfo contains the information of the target such as network address and metadata.
  427. type TargetInfo struct {
  428. Addr string
  429. Metadata interface{}
  430. Authority string
  431. }
  432. // NewClientTransport establishes the transport with the required ConnectOptions
  433. // and returns it to the caller.
  434. func NewClientTransport(connectCtx, ctx context.Context, target TargetInfo, opts ConnectOptions, onSuccess func()) (ClientTransport, error) {
  435. return newHTTP2Client(connectCtx, ctx, target, opts, onSuccess)
  436. }
  437. // Options provides additional hints and information for message
  438. // transmission.
  439. type Options struct {
  440. // Last indicates whether this write is the last piece for
  441. // this stream.
  442. Last bool
  443. // Delay is a hint to the transport implementation for whether
  444. // the data could be buffered for a batching write. The
  445. // transport implementation may ignore the hint.
  446. Delay bool
  447. }
  448. // CallHdr carries the information of a particular RPC.
  449. type CallHdr struct {
  450. // Host specifies the peer's host.
  451. Host string
  452. // Method specifies the operation to perform.
  453. Method string
  454. // SendCompress specifies the compression algorithm applied on
  455. // outbound message.
  456. SendCompress string
  457. // Creds specifies credentials.PerRPCCredentials for a call.
  458. Creds credentials.PerRPCCredentials
  459. // Flush indicates whether a new stream command should be sent
  460. // to the peer without waiting for the first data. This is
  461. // only a hint.
  462. // If it's true, the transport may modify the flush decision
  463. // for performance purposes.
  464. // If it's false, new stream will never be flushed.
  465. Flush bool
  466. // ContentSubtype specifies the content-subtype for a request. For example, a
  467. // content-subtype of "proto" will result in a content-type of
  468. // "application/grpc+proto". The value of ContentSubtype must be all
  469. // lowercase, otherwise the behavior is undefined. See
  470. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
  471. // for more details.
  472. ContentSubtype string
  473. }
  474. // ClientTransport is the common interface for all gRPC client-side transport
  475. // implementations.
  476. type ClientTransport interface {
  477. // Close tears down this transport. Once it returns, the transport
  478. // should not be accessed any more. The caller must make sure this
  479. // is called only once.
  480. Close() error
  481. // GracefulClose starts to tear down the transport. It stops accepting
  482. // new RPCs and wait the completion of the pending RPCs.
  483. GracefulClose() error
  484. // Write sends the data for the given stream. A nil stream indicates
  485. // the write is to be performed on the transport as a whole.
  486. Write(s *Stream, hdr []byte, data []byte, opts *Options) error
  487. // NewStream creates a Stream for an RPC.
  488. NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error)
  489. // CloseStream clears the footprint of a stream when the stream is
  490. // not needed any more. The err indicates the error incurred when
  491. // CloseStream is called. Must be called when a stream is finished
  492. // unless the associated transport is closing.
  493. CloseStream(stream *Stream, err error)
  494. // Error returns a channel that is closed when some I/O error
  495. // happens. Typically the caller should have a goroutine to monitor
  496. // this in order to take action (e.g., close the current transport
  497. // and create a new one) in error case. It should not return nil
  498. // once the transport is initiated.
  499. Error() <-chan struct{}
  500. // GoAway returns a channel that is closed when ClientTransport
  501. // receives the draining signal from the server (e.g., GOAWAY frame in
  502. // HTTP/2).
  503. GoAway() <-chan struct{}
  504. // GetGoAwayReason returns the reason why GoAway frame was received.
  505. GetGoAwayReason() GoAwayReason
  506. // IncrMsgSent increments the number of message sent through this transport.
  507. IncrMsgSent()
  508. // IncrMsgRecv increments the number of message received through this transport.
  509. IncrMsgRecv()
  510. }
  511. // ServerTransport is the common interface for all gRPC server-side transport
  512. // implementations.
  513. //
  514. // Methods may be called concurrently from multiple goroutines, but
  515. // Write methods for a given Stream will be called serially.
  516. type ServerTransport interface {
  517. // HandleStreams receives incoming streams using the given handler.
  518. HandleStreams(func(*Stream), func(context.Context, string) context.Context)
  519. // WriteHeader sends the header metadata for the given stream.
  520. // WriteHeader may not be called on all streams.
  521. WriteHeader(s *Stream, md metadata.MD) error
  522. // Write sends the data for the given stream.
  523. // Write may not be called on all streams.
  524. Write(s *Stream, hdr []byte, data []byte, opts *Options) error
  525. // WriteStatus sends the status of a stream to the client. WriteStatus is
  526. // the final call made on a stream and always occurs.
  527. WriteStatus(s *Stream, st *status.Status) error
  528. // Close tears down the transport. Once it is called, the transport
  529. // should not be accessed any more. All the pending streams and their
  530. // handlers will be terminated asynchronously.
  531. Close() error
  532. // RemoteAddr returns the remote network address.
  533. RemoteAddr() net.Addr
  534. // Drain notifies the client this ServerTransport stops accepting new RPCs.
  535. Drain()
  536. // IncrMsgSent increments the number of message sent through this transport.
  537. IncrMsgSent()
  538. // IncrMsgRecv increments the number of message received through this transport.
  539. IncrMsgRecv()
  540. }
  541. // streamErrorf creates an StreamError with the specified error code and description.
  542. func streamErrorf(c codes.Code, format string, a ...interface{}) StreamError {
  543. return StreamError{
  544. Code: c,
  545. Desc: fmt.Sprintf(format, a...),
  546. }
  547. }
  548. // connectionErrorf creates an ConnectionError with the specified error description.
  549. func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError {
  550. return ConnectionError{
  551. Desc: fmt.Sprintf(format, a...),
  552. temp: temp,
  553. err: e,
  554. }
  555. }
  556. // ConnectionError is an error that results in the termination of the
  557. // entire connection and the retry of all the active streams.
  558. type ConnectionError struct {
  559. Desc string
  560. temp bool
  561. err error
  562. }
  563. func (e ConnectionError) Error() string {
  564. return fmt.Sprintf("connection error: desc = %q", e.Desc)
  565. }
  566. // Temporary indicates if this connection error is temporary or fatal.
  567. func (e ConnectionError) Temporary() bool {
  568. return e.temp
  569. }
  570. // Origin returns the original error of this connection error.
  571. func (e ConnectionError) Origin() error {
  572. // Never return nil error here.
  573. // If the original error is nil, return itself.
  574. if e.err == nil {
  575. return e
  576. }
  577. return e.err
  578. }
  579. var (
  580. // ErrConnClosing indicates that the transport is closing.
  581. ErrConnClosing = connectionErrorf(true, nil, "transport is closing")
  582. // errStreamDrain indicates that the stream is rejected because the
  583. // connection is draining. This could be caused by goaway or balancer
  584. // removing the address.
  585. errStreamDrain = streamErrorf(codes.Unavailable, "the connection is draining")
  586. // errStreamDone is returned from write at the client side to indiacte application
  587. // layer of an error.
  588. errStreamDone = errors.New("the stream is done")
  589. // StatusGoAway indicates that the server sent a GOAWAY that included this
  590. // stream's ID in unprocessed RPCs.
  591. statusGoAway = status.New(codes.Unavailable, "the stream is rejected because server is draining the connection")
  592. )
  593. // TODO: See if we can replace StreamError with status package errors.
  594. // StreamError is an error that only affects one stream within a connection.
  595. type StreamError struct {
  596. Code codes.Code
  597. Desc string
  598. }
  599. func (e StreamError) Error() string {
  600. return fmt.Sprintf("stream error: code = %s desc = %q", e.Code, e.Desc)
  601. }
  602. // GoAwayReason contains the reason for the GoAway frame received.
  603. type GoAwayReason uint8
  604. const (
  605. // GoAwayInvalid indicates that no GoAway frame is received.
  606. GoAwayInvalid GoAwayReason = 0
  607. // GoAwayNoReason is the default value when GoAway frame is received.
  608. GoAwayNoReason GoAwayReason = 1
  609. // GoAwayTooManyPings indicates that a GoAway frame with
  610. // ErrCodeEnhanceYourCalm was received and that the debug data said
  611. // "too_many_pings".
  612. GoAwayTooManyPings GoAwayReason = 2
  613. )