controlbuf.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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
  19. import (
  20. "bytes"
  21. "fmt"
  22. "runtime"
  23. "sync"
  24. "golang.org/x/net/http2"
  25. "golang.org/x/net/http2/hpack"
  26. )
  27. var updateHeaderTblSize = func(e *hpack.Encoder, v uint32) {
  28. e.SetMaxDynamicTableSizeLimit(v)
  29. }
  30. type itemNode struct {
  31. it interface{}
  32. next *itemNode
  33. }
  34. type itemList struct {
  35. head *itemNode
  36. tail *itemNode
  37. }
  38. func (il *itemList) enqueue(i interface{}) {
  39. n := &itemNode{it: i}
  40. if il.tail == nil {
  41. il.head, il.tail = n, n
  42. return
  43. }
  44. il.tail.next = n
  45. il.tail = n
  46. }
  47. // peek returns the first item in the list without removing it from the
  48. // list.
  49. func (il *itemList) peek() interface{} {
  50. return il.head.it
  51. }
  52. func (il *itemList) dequeue() interface{} {
  53. if il.head == nil {
  54. return nil
  55. }
  56. i := il.head.it
  57. il.head = il.head.next
  58. if il.head == nil {
  59. il.tail = nil
  60. }
  61. return i
  62. }
  63. func (il *itemList) dequeueAll() *itemNode {
  64. h := il.head
  65. il.head, il.tail = nil, nil
  66. return h
  67. }
  68. func (il *itemList) isEmpty() bool {
  69. return il.head == nil
  70. }
  71. // The following defines various control items which could flow through
  72. // the control buffer of transport. They represent different aspects of
  73. // control tasks, e.g., flow control, settings, streaming resetting, etc.
  74. // registerStream is used to register an incoming stream with loopy writer.
  75. type registerStream struct {
  76. streamID uint32
  77. wq *writeQuota
  78. }
  79. // headerFrame is also used to register stream on the client-side.
  80. type headerFrame struct {
  81. streamID uint32
  82. hf []hpack.HeaderField
  83. endStream bool // Valid on server side.
  84. initStream func(uint32) (bool, error) // Used only on the client side.
  85. onWrite func()
  86. wq *writeQuota // write quota for the stream created.
  87. cleanup *cleanupStream // Valid on the server side.
  88. onOrphaned func(error) // Valid on client-side
  89. }
  90. type cleanupStream struct {
  91. streamID uint32
  92. idPtr *uint32
  93. rst bool
  94. rstCode http2.ErrCode
  95. onWrite func()
  96. }
  97. type dataFrame struct {
  98. streamID uint32
  99. endStream bool
  100. h []byte
  101. d []byte
  102. // onEachWrite is called every time
  103. // a part of d is written out.
  104. onEachWrite func()
  105. }
  106. type incomingWindowUpdate struct {
  107. streamID uint32
  108. increment uint32
  109. }
  110. type outgoingWindowUpdate struct {
  111. streamID uint32
  112. increment uint32
  113. }
  114. type incomingSettings struct {
  115. ss []http2.Setting
  116. }
  117. type outgoingSettings struct {
  118. ss []http2.Setting
  119. }
  120. type settingsAck struct {
  121. }
  122. type incomingGoAway struct {
  123. }
  124. type goAway struct {
  125. code http2.ErrCode
  126. debugData []byte
  127. headsUp bool
  128. closeConn bool
  129. }
  130. type ping struct {
  131. ack bool
  132. data [8]byte
  133. }
  134. type outFlowControlSizeRequest struct {
  135. resp chan uint32
  136. }
  137. type outStreamState int
  138. const (
  139. active outStreamState = iota
  140. empty
  141. waitingOnStreamQuota
  142. )
  143. type outStream struct {
  144. id uint32
  145. state outStreamState
  146. itl *itemList
  147. bytesOutStanding int
  148. wq *writeQuota
  149. next *outStream
  150. prev *outStream
  151. }
  152. func (s *outStream) deleteSelf() {
  153. if s.prev != nil {
  154. s.prev.next = s.next
  155. }
  156. if s.next != nil {
  157. s.next.prev = s.prev
  158. }
  159. s.next, s.prev = nil, nil
  160. }
  161. type outStreamList struct {
  162. // Following are sentinel objects that mark the
  163. // beginning and end of the list. They do not
  164. // contain any item lists. All valid objects are
  165. // inserted in between them.
  166. // This is needed so that an outStream object can
  167. // deleteSelf() in O(1) time without knowing which
  168. // list it belongs to.
  169. head *outStream
  170. tail *outStream
  171. }
  172. func newOutStreamList() *outStreamList {
  173. head, tail := new(outStream), new(outStream)
  174. head.next = tail
  175. tail.prev = head
  176. return &outStreamList{
  177. head: head,
  178. tail: tail,
  179. }
  180. }
  181. func (l *outStreamList) enqueue(s *outStream) {
  182. e := l.tail.prev
  183. e.next = s
  184. s.prev = e
  185. s.next = l.tail
  186. l.tail.prev = s
  187. }
  188. // remove from the beginning of the list.
  189. func (l *outStreamList) dequeue() *outStream {
  190. b := l.head.next
  191. if b == l.tail {
  192. return nil
  193. }
  194. b.deleteSelf()
  195. return b
  196. }
  197. // controlBuffer is a way to pass information to loopy.
  198. // Information is passed as specific struct types called control frames.
  199. // A control frame not only represents data, messages or headers to be sent out
  200. // but can also be used to instruct loopy to update its internal state.
  201. // It shouldn't be confused with an HTTP2 frame, although some of the control frames
  202. // like dataFrame and headerFrame do go out on wire as HTTP2 frames.
  203. type controlBuffer struct {
  204. ch chan struct{}
  205. done <-chan struct{}
  206. mu sync.Mutex
  207. consumerWaiting bool
  208. list *itemList
  209. err error
  210. }
  211. func newControlBuffer(done <-chan struct{}) *controlBuffer {
  212. return &controlBuffer{
  213. ch: make(chan struct{}, 1),
  214. list: &itemList{},
  215. done: done,
  216. }
  217. }
  218. func (c *controlBuffer) put(it interface{}) error {
  219. _, err := c.executeAndPut(nil, it)
  220. return err
  221. }
  222. func (c *controlBuffer) executeAndPut(f func(it interface{}) bool, it interface{}) (bool, error) {
  223. var wakeUp bool
  224. c.mu.Lock()
  225. if c.err != nil {
  226. c.mu.Unlock()
  227. return false, c.err
  228. }
  229. if f != nil {
  230. if !f(it) { // f wasn't successful
  231. c.mu.Unlock()
  232. return false, nil
  233. }
  234. }
  235. if c.consumerWaiting {
  236. wakeUp = true
  237. c.consumerWaiting = false
  238. }
  239. c.list.enqueue(it)
  240. c.mu.Unlock()
  241. if wakeUp {
  242. select {
  243. case c.ch <- struct{}{}:
  244. default:
  245. }
  246. }
  247. return true, nil
  248. }
  249. // Note argument f should never be nil.
  250. func (c *controlBuffer) execute(f func(it interface{}) bool, it interface{}) (bool, error) {
  251. c.mu.Lock()
  252. if c.err != nil {
  253. c.mu.Unlock()
  254. return false, c.err
  255. }
  256. if !f(it) { // f wasn't successful
  257. c.mu.Unlock()
  258. return false, nil
  259. }
  260. c.mu.Unlock()
  261. return true, nil
  262. }
  263. func (c *controlBuffer) get(block bool) (interface{}, error) {
  264. for {
  265. c.mu.Lock()
  266. if c.err != nil {
  267. c.mu.Unlock()
  268. return nil, c.err
  269. }
  270. if !c.list.isEmpty() {
  271. h := c.list.dequeue()
  272. c.mu.Unlock()
  273. return h, nil
  274. }
  275. if !block {
  276. c.mu.Unlock()
  277. return nil, nil
  278. }
  279. c.consumerWaiting = true
  280. c.mu.Unlock()
  281. select {
  282. case <-c.ch:
  283. case <-c.done:
  284. c.finish()
  285. return nil, ErrConnClosing
  286. }
  287. }
  288. }
  289. func (c *controlBuffer) finish() {
  290. c.mu.Lock()
  291. if c.err != nil {
  292. c.mu.Unlock()
  293. return
  294. }
  295. c.err = ErrConnClosing
  296. // There may be headers for streams in the control buffer.
  297. // These streams need to be cleaned out since the transport
  298. // is still not aware of these yet.
  299. for head := c.list.dequeueAll(); head != nil; head = head.next {
  300. hdr, ok := head.it.(*headerFrame)
  301. if !ok {
  302. continue
  303. }
  304. if hdr.onOrphaned != nil { // It will be nil on the server-side.
  305. hdr.onOrphaned(ErrConnClosing)
  306. }
  307. }
  308. c.mu.Unlock()
  309. }
  310. type side int
  311. const (
  312. clientSide side = iota
  313. serverSide
  314. )
  315. // Loopy receives frames from the control buffer.
  316. // Each frame is handled individually; most of the work done by loopy goes
  317. // into handling data frames. Loopy maintains a queue of active streams, and each
  318. // stream maintains a queue of data frames; as loopy receives data frames
  319. // it gets added to the queue of the relevant stream.
  320. // Loopy goes over this list of active streams by processing one node every iteration,
  321. // thereby closely resemebling to a round-robin scheduling over all streams. While
  322. // processing a stream, loopy writes out data bytes from this stream capped by the min
  323. // of http2MaxFrameLen, connection-level flow control and stream-level flow control.
  324. type loopyWriter struct {
  325. side side
  326. cbuf *controlBuffer
  327. sendQuota uint32
  328. oiws uint32 // outbound initial window size.
  329. // estdStreams is map of all established streams that are not cleaned-up yet.
  330. // On client-side, this is all streams whose headers were sent out.
  331. // On server-side, this is all streams whose headers were received.
  332. estdStreams map[uint32]*outStream // Established streams.
  333. // activeStreams is a linked-list of all streams that have data to send and some
  334. // stream-level flow control quota.
  335. // Each of these streams internally have a list of data items(and perhaps trailers
  336. // on the server-side) to be sent out.
  337. activeStreams *outStreamList
  338. framer *framer
  339. hBuf *bytes.Buffer // The buffer for HPACK encoding.
  340. hEnc *hpack.Encoder // HPACK encoder.
  341. bdpEst *bdpEstimator
  342. draining bool
  343. // Side-specific handlers
  344. ssGoAwayHandler func(*goAway) (bool, error)
  345. }
  346. func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimator) *loopyWriter {
  347. var buf bytes.Buffer
  348. l := &loopyWriter{
  349. side: s,
  350. cbuf: cbuf,
  351. sendQuota: defaultWindowSize,
  352. oiws: defaultWindowSize,
  353. estdStreams: make(map[uint32]*outStream),
  354. activeStreams: newOutStreamList(),
  355. framer: fr,
  356. hBuf: &buf,
  357. hEnc: hpack.NewEncoder(&buf),
  358. bdpEst: bdpEst,
  359. }
  360. return l
  361. }
  362. const minBatchSize = 1000
  363. // run should be run in a separate goroutine.
  364. // It reads control frames from controlBuf and processes them by:
  365. // 1. Updating loopy's internal state, or/and
  366. // 2. Writing out HTTP2 frames on the wire.
  367. //
  368. // Loopy keeps all active streams with data to send in a linked-list.
  369. // All streams in the activeStreams linked-list must have both:
  370. // 1. Data to send, and
  371. // 2. Stream level flow control quota available.
  372. //
  373. // In each iteration of run loop, other than processing the incoming control
  374. // frame, loopy calls processData, which processes one node from the activeStreams linked-list.
  375. // This results in writing of HTTP2 frames into an underlying write buffer.
  376. // When there's no more control frames to read from controlBuf, loopy flushes the write buffer.
  377. // As an optimization, to increase the batch size for each flush, loopy yields the processor, once
  378. // if the batch size is too low to give stream goroutines a chance to fill it up.
  379. func (l *loopyWriter) run() (err error) {
  380. defer func() {
  381. if err == ErrConnClosing {
  382. // Don't log ErrConnClosing as error since it happens
  383. // 1. When the connection is closed by some other known issue.
  384. // 2. User closed the connection.
  385. // 3. A graceful close of connection.
  386. infof("transport: loopyWriter.run returning. %v", err)
  387. err = nil
  388. }
  389. }()
  390. for {
  391. it, err := l.cbuf.get(true)
  392. if err != nil {
  393. return err
  394. }
  395. if err = l.handle(it); err != nil {
  396. return err
  397. }
  398. if _, err = l.processData(); err != nil {
  399. return err
  400. }
  401. gosched := true
  402. hasdata:
  403. for {
  404. it, err := l.cbuf.get(false)
  405. if err != nil {
  406. return err
  407. }
  408. if it != nil {
  409. if err = l.handle(it); err != nil {
  410. return err
  411. }
  412. if _, err = l.processData(); err != nil {
  413. return err
  414. }
  415. continue hasdata
  416. }
  417. isEmpty, err := l.processData()
  418. if err != nil {
  419. return err
  420. }
  421. if !isEmpty {
  422. continue hasdata
  423. }
  424. if gosched {
  425. gosched = false
  426. if l.framer.writer.offset < minBatchSize {
  427. runtime.Gosched()
  428. continue hasdata
  429. }
  430. }
  431. l.framer.writer.Flush()
  432. break hasdata
  433. }
  434. }
  435. }
  436. func (l *loopyWriter) outgoingWindowUpdateHandler(w *outgoingWindowUpdate) error {
  437. return l.framer.fr.WriteWindowUpdate(w.streamID, w.increment)
  438. }
  439. func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) error {
  440. // Otherwise update the quota.
  441. if w.streamID == 0 {
  442. l.sendQuota += w.increment
  443. return nil
  444. }
  445. // Find the stream and update it.
  446. if str, ok := l.estdStreams[w.streamID]; ok {
  447. str.bytesOutStanding -= int(w.increment)
  448. if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota > 0 && str.state == waitingOnStreamQuota {
  449. str.state = active
  450. l.activeStreams.enqueue(str)
  451. return nil
  452. }
  453. }
  454. return nil
  455. }
  456. func (l *loopyWriter) outgoingSettingsHandler(s *outgoingSettings) error {
  457. return l.framer.fr.WriteSettings(s.ss...)
  458. }
  459. func (l *loopyWriter) incomingSettingsHandler(s *incomingSettings) error {
  460. if err := l.applySettings(s.ss); err != nil {
  461. return err
  462. }
  463. return l.framer.fr.WriteSettingsAck()
  464. }
  465. func (l *loopyWriter) registerStreamHandler(h *registerStream) error {
  466. str := &outStream{
  467. id: h.streamID,
  468. state: empty,
  469. itl: &itemList{},
  470. wq: h.wq,
  471. }
  472. l.estdStreams[h.streamID] = str
  473. return nil
  474. }
  475. func (l *loopyWriter) headerHandler(h *headerFrame) error {
  476. if l.side == serverSide {
  477. str, ok := l.estdStreams[h.streamID]
  478. if !ok {
  479. warningf("transport: loopy doesn't recognize the stream: %d", h.streamID)
  480. return nil
  481. }
  482. // Case 1.A: Server is responding back with headers.
  483. if !h.endStream {
  484. return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite)
  485. }
  486. // else: Case 1.B: Server wants to close stream.
  487. if str.state != empty { // either active or waiting on stream quota.
  488. // add it str's list of items.
  489. str.itl.enqueue(h)
  490. return nil
  491. }
  492. if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil {
  493. return err
  494. }
  495. return l.cleanupStreamHandler(h.cleanup)
  496. }
  497. // Case 2: Client wants to originate stream.
  498. str := &outStream{
  499. id: h.streamID,
  500. state: empty,
  501. itl: &itemList{},
  502. wq: h.wq,
  503. }
  504. str.itl.enqueue(h)
  505. return l.originateStream(str)
  506. }
  507. func (l *loopyWriter) originateStream(str *outStream) error {
  508. hdr := str.itl.dequeue().(*headerFrame)
  509. sendPing, err := hdr.initStream(str.id)
  510. if err != nil {
  511. if err == ErrConnClosing {
  512. return err
  513. }
  514. // Other errors(errStreamDrain) need not close transport.
  515. return nil
  516. }
  517. if err = l.writeHeader(str.id, hdr.endStream, hdr.hf, hdr.onWrite); err != nil {
  518. return err
  519. }
  520. l.estdStreams[str.id] = str
  521. if sendPing {
  522. return l.pingHandler(&ping{data: [8]byte{}})
  523. }
  524. return nil
  525. }
  526. func (l *loopyWriter) writeHeader(streamID uint32, endStream bool, hf []hpack.HeaderField, onWrite func()) error {
  527. if onWrite != nil {
  528. onWrite()
  529. }
  530. l.hBuf.Reset()
  531. for _, f := range hf {
  532. if err := l.hEnc.WriteField(f); err != nil {
  533. warningf("transport: loopyWriter.writeHeader encountered error while encoding headers:", err)
  534. }
  535. }
  536. var (
  537. err error
  538. endHeaders, first bool
  539. )
  540. first = true
  541. for !endHeaders {
  542. size := l.hBuf.Len()
  543. if size > http2MaxFrameLen {
  544. size = http2MaxFrameLen
  545. } else {
  546. endHeaders = true
  547. }
  548. if first {
  549. first = false
  550. err = l.framer.fr.WriteHeaders(http2.HeadersFrameParam{
  551. StreamID: streamID,
  552. BlockFragment: l.hBuf.Next(size),
  553. EndStream: endStream,
  554. EndHeaders: endHeaders,
  555. })
  556. } else {
  557. err = l.framer.fr.WriteContinuation(
  558. streamID,
  559. endHeaders,
  560. l.hBuf.Next(size),
  561. )
  562. }
  563. if err != nil {
  564. return err
  565. }
  566. }
  567. return nil
  568. }
  569. func (l *loopyWriter) preprocessData(df *dataFrame) error {
  570. str, ok := l.estdStreams[df.streamID]
  571. if !ok {
  572. return nil
  573. }
  574. // If we got data for a stream it means that
  575. // stream was originated and the headers were sent out.
  576. str.itl.enqueue(df)
  577. if str.state == empty {
  578. str.state = active
  579. l.activeStreams.enqueue(str)
  580. }
  581. return nil
  582. }
  583. func (l *loopyWriter) pingHandler(p *ping) error {
  584. if !p.ack {
  585. l.bdpEst.timesnap(p.data)
  586. }
  587. return l.framer.fr.WritePing(p.ack, p.data)
  588. }
  589. func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequest) error {
  590. o.resp <- l.sendQuota
  591. return nil
  592. }
  593. func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error {
  594. c.onWrite()
  595. if str, ok := l.estdStreams[c.streamID]; ok {
  596. // On the server side it could be a trailers-only response or
  597. // a RST_STREAM before stream initialization thus the stream might
  598. // not be established yet.
  599. delete(l.estdStreams, c.streamID)
  600. str.deleteSelf()
  601. }
  602. if c.rst { // If RST_STREAM needs to be sent.
  603. if err := l.framer.fr.WriteRSTStream(c.streamID, c.rstCode); err != nil {
  604. return err
  605. }
  606. }
  607. if l.side == clientSide && l.draining && len(l.estdStreams) == 0 {
  608. return ErrConnClosing
  609. }
  610. return nil
  611. }
  612. func (l *loopyWriter) incomingGoAwayHandler(*incomingGoAway) error {
  613. if l.side == clientSide {
  614. l.draining = true
  615. if len(l.estdStreams) == 0 {
  616. return ErrConnClosing
  617. }
  618. }
  619. return nil
  620. }
  621. func (l *loopyWriter) goAwayHandler(g *goAway) error {
  622. // Handling of outgoing GoAway is very specific to side.
  623. if l.ssGoAwayHandler != nil {
  624. draining, err := l.ssGoAwayHandler(g)
  625. if err != nil {
  626. return err
  627. }
  628. l.draining = draining
  629. }
  630. return nil
  631. }
  632. func (l *loopyWriter) handle(i interface{}) error {
  633. switch i := i.(type) {
  634. case *incomingWindowUpdate:
  635. return l.incomingWindowUpdateHandler(i)
  636. case *outgoingWindowUpdate:
  637. return l.outgoingWindowUpdateHandler(i)
  638. case *incomingSettings:
  639. return l.incomingSettingsHandler(i)
  640. case *outgoingSettings:
  641. return l.outgoingSettingsHandler(i)
  642. case *headerFrame:
  643. return l.headerHandler(i)
  644. case *registerStream:
  645. return l.registerStreamHandler(i)
  646. case *cleanupStream:
  647. return l.cleanupStreamHandler(i)
  648. case *incomingGoAway:
  649. return l.incomingGoAwayHandler(i)
  650. case *dataFrame:
  651. return l.preprocessData(i)
  652. case *ping:
  653. return l.pingHandler(i)
  654. case *goAway:
  655. return l.goAwayHandler(i)
  656. case *outFlowControlSizeRequest:
  657. return l.outFlowControlSizeRequestHandler(i)
  658. default:
  659. return fmt.Errorf("transport: unknown control message type %T", i)
  660. }
  661. }
  662. func (l *loopyWriter) applySettings(ss []http2.Setting) error {
  663. for _, s := range ss {
  664. switch s.ID {
  665. case http2.SettingInitialWindowSize:
  666. o := l.oiws
  667. l.oiws = s.Val
  668. if o < l.oiws {
  669. // If the new limit is greater make all depleted streams active.
  670. for _, stream := range l.estdStreams {
  671. if stream.state == waitingOnStreamQuota {
  672. stream.state = active
  673. l.activeStreams.enqueue(stream)
  674. }
  675. }
  676. }
  677. case http2.SettingHeaderTableSize:
  678. updateHeaderTblSize(l.hEnc, s.Val)
  679. }
  680. }
  681. return nil
  682. }
  683. // processData removes the first stream from active streams, writes out at most 16KB
  684. // of its data and then puts it at the end of activeStreams if there's still more data
  685. // to be sent and stream has some stream-level flow control.
  686. func (l *loopyWriter) processData() (bool, error) {
  687. if l.sendQuota == 0 {
  688. return true, nil
  689. }
  690. str := l.activeStreams.dequeue() // Remove the first stream.
  691. if str == nil {
  692. return true, nil
  693. }
  694. dataItem := str.itl.peek().(*dataFrame) // Peek at the first data item this stream.
  695. // A data item is represented by a dataFrame, since it later translates into
  696. // multiple HTTP2 data frames.
  697. // Every dataFrame has two buffers; h that keeps grpc-message header and d that is acutal data.
  698. // As an optimization to keep wire traffic low, data from d is copied to h to make as big as the
  699. // maximum possilbe HTTP2 frame size.
  700. if len(dataItem.h) == 0 && len(dataItem.d) == 0 { // Empty data frame
  701. // Client sends out empty data frame with endStream = true
  702. if err := l.framer.fr.WriteData(dataItem.streamID, dataItem.endStream, nil); err != nil {
  703. return false, err
  704. }
  705. str.itl.dequeue() // remove the empty data item from stream
  706. if str.itl.isEmpty() {
  707. str.state = empty
  708. } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers.
  709. if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil {
  710. return false, err
  711. }
  712. if err := l.cleanupStreamHandler(trailer.cleanup); err != nil {
  713. return false, nil
  714. }
  715. } else {
  716. l.activeStreams.enqueue(str)
  717. }
  718. return false, nil
  719. }
  720. var (
  721. idx int
  722. buf []byte
  723. )
  724. if len(dataItem.h) != 0 { // data header has not been written out yet.
  725. buf = dataItem.h
  726. } else {
  727. idx = 1
  728. buf = dataItem.d
  729. }
  730. size := http2MaxFrameLen
  731. if len(buf) < size {
  732. size = len(buf)
  733. }
  734. if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 { // stream-level flow control.
  735. str.state = waitingOnStreamQuota
  736. return false, nil
  737. } else if strQuota < size {
  738. size = strQuota
  739. }
  740. if l.sendQuota < uint32(size) { // connection-level flow control.
  741. size = int(l.sendQuota)
  742. }
  743. // Now that outgoing flow controls are checked we can replenish str's write quota
  744. str.wq.replenish(size)
  745. var endStream bool
  746. // If this is the last data message on this stream and all of it can be written in this iteration.
  747. if dataItem.endStream && size == len(buf) {
  748. // buf contains either data or it contains header but data is empty.
  749. if idx == 1 || len(dataItem.d) == 0 {
  750. endStream = true
  751. }
  752. }
  753. if dataItem.onEachWrite != nil {
  754. dataItem.onEachWrite()
  755. }
  756. if err := l.framer.fr.WriteData(dataItem.streamID, endStream, buf[:size]); err != nil {
  757. return false, err
  758. }
  759. buf = buf[size:]
  760. str.bytesOutStanding += size
  761. l.sendQuota -= uint32(size)
  762. if idx == 0 {
  763. dataItem.h = buf
  764. } else {
  765. dataItem.d = buf
  766. }
  767. if len(dataItem.h) == 0 && len(dataItem.d) == 0 { // All the data from that message was written out.
  768. str.itl.dequeue()
  769. }
  770. if str.itl.isEmpty() {
  771. str.state = empty
  772. } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // The next item is trailers.
  773. if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil {
  774. return false, err
  775. }
  776. if err := l.cleanupStreamHandler(trailer.cleanup); err != nil {
  777. return false, err
  778. }
  779. } else if int(l.oiws)-str.bytesOutStanding <= 0 { // Ran out of stream quota.
  780. str.state = waitingOnStreamQuota
  781. } else { // Otherwise add it back to the list of active streams.
  782. l.activeStreams.enqueue(str)
  783. }
  784. return false, nil
  785. }